Fortran数组字符串

时间:2014-11-13 23:09:00

标签: character-encoding fortran

我在填充字符串数组时遇到问题。 使用[]声明分配元素时会发生此问题 在数组中。当我为数组元素分配我的元素时,一切 很好。

这是输出

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]

1 个答案:

答案 0 :(得分:1)

解决方案是在数组构造函数

中包含字符长度参数
str = [Character(len=65) :: a1,a2,a3,a4,a5,a6,a7]