【问题标题】:Fortran Array of StringsFortran 字符串数组
【发布时间】:2015-01-11 06:22:06
【问题描述】:

我在填充字符串数组时遇到问题。 使用[]声明分配元素时出现问题 在一个数组中。当我将数组元素分配给我的元素时,一切 很好。

这是输出

Expected Output: redgreenyellowblue
Actual output: redgreyelblue

这里是代码

Character (len=*), Intent(in), Optional :: a2,     &
                           a3, a4, a5, a6, a7, a8  

Character (len=65), Allocatable :: str(:)
Character (len=65) :: b(512)

a1 = "red"
a2 = "green"
a3 = "yellow"
a4 = "blue"
a5 = "magenta"
a6 = "cyan"
a7 = "white"

Allocate (str(7))

str = [a1, a2, a3, a4, a5, a6, a7]

str(4) = a4
str(5) = a5
str(6) = a6
str(7) = a7

Write (*,*) "Expected output: ", Trim(a1), Trim(a2), Trim(a3), Trim(a4)
Write (*,*) "Actual output: ", Trim(str(1)), Trim(str(2)), Trim(str(3)), Trim(str(4))

我已确认以下内容按预期工作

Character (len=65), Allocatable :: str(:)
Character (len=65) :: a1, a2, a3, a4, a5, a6, a7

a1 = "red" ; a2 = "green"; a3 = "yellow"; a4 = "blue"
a5 = "magenta";  a6 = "cyan"; a7 ="white"

Allocate (str(7))
str = [a1,a2,a3,a4,a5,a6,a7]
Write (*,*) Trim(a1), Trim(a2), Trim(a3), Trim(a4), Trim(a5)
Write (*,*) Trim(str(1)), Trim(str(2)), Trim(str(3)), Trim(str(4)), Trim(str(5))
Deallocate (str)

解决方法是在构造函数中包含字符长度参数

str = [Character(len=65) :: a1,a2,a3,a4,a5,a6,a7]

【问题讨论】:

  • 首先,有什么问题?你得到一个编译器错误吗?如果是,请报告错误。如果你只是得到垃圾输出,请说明你得到的输出。其次,我很确定 [] 表示法是无效的 Fortran (除非它在较新的标准之一中)...
  • 你的意思是像(/ a1, a2, a3, a4, a5, a6, a7 /)这样的吗?
  • 随着您的新更新,很明显这是因为您将len=* 用于“a”变量,并且数组构造函数假定所有变量的长度与第一个元素(“红色”,所以 3)。
  • 参见stackoverflow.com/q/21552430/3157076关于从不同长度变量构造的信息。
  • 你不需要计算as的最长长度:使用str的length-65即可。

标签: character-encoding fortran


【解决方案1】:

解决方法是在数组构造函数中包含字符长度参数

str = [Character(len=65) :: a1,a2,a3,a4,a5,a6,a7]

【讨论】:

  • 这是不正确的 Fortran。
猜你喜欢
  • 2018-10-08
  • 2010-10-18
  • 2021-09-05
  • 2014-10-25
  • 1970-01-01
  • 2020-01-23
  • 1970-01-01
  • 1970-01-01
  • 2015-08-07
相关资源
最近更新 更多