'Fortran Array of Strings [duplicate]
I am encountering a problem filling an array of character strings. The problem occurs when using the [] declaration to assign elements in an array. When I assign the array element my element, everything is fine.
This is the output
Expected Output: redgreenyellowblue
Actual output: redgreyelblue
Here is the code
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))
I have conformed that the following works as expected
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)
The solution is to include the character length parameter in the constructor
str = [Character(len=65) :: a1,a2,a3,a4,a5,a6,a7]
Solution 1:[1]
The solution is to include the character length parameter in the array constructor
str = [Character(len=65) :: a1,a2,a3,a4,a5,a6,a7]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Zeus |
