问题
I would like to evaluate if the 3rd letter of variable myline is 'C' or not.
I try this:
program main
implicit none
type line
integer :: count = 5
character(len=48) :: list = 'ABCDE'
end type
type(line) :: myline
character(len=1) :: letter = 'C'
write(*,*) myline%count, myline%list
if(myline%list(3) == letter) then
write(*,*) 'TRUE'
else
write(*,*) 'FALSE'
end if
end program
But I get:
$ /usr/local/bin/gfortran8 -mcmodel=medium -fcheck=all -Wl,-rpath=/usr/local/lib/gcc8 -o test test.f90
test.f90:15:15:
if(myline%list(3) == letter) then
1
Error: Syntax error in IF-expression at (1)
test.f90:17:5:
else
1
Error: Unexpected ELSE statement at (1)
test.f90:19:4:
end if
1
Error: Expecting END PROGRAM statement at (1)
I am using gfortran (gcc8) and the Fortran 90 standard.
回答1:
In Fortran, a character substring reference always needs a start and end position. So what you want here is myline%list(3:3)
.
You can omit the end position (retaining the colon), for example (3:)
, and that means the rest of the string. Similarly you can omit the start position and it means from the first character (:3)
.
As a suggestion, letter
would be better declared with the parameter
attribute as it is a constant, but what you have would work.
来源:https://stackoverflow.com/questions/57898173/evaluating-a-specific-letter-of-a-string-defined-in-a-derived-type-in-fortran90