1

我想澄清一下 Fortran 处理字符串中“空”字符的方式。让我们假设我们有这种情况:

program main
implicit none

test('AB')
end program

在哪里

function test(name)
implicit none
character(10) :: name
character(3)  :: cutname

write(*,*) '-'//name//'-'             ! Gives output "-AB        -" 
                                      ! Space has then been added at the end
cutname(1:3) = name(1:3)
write(*,*) '1-'//cutname//'-'           ! Gives output "-AB -"
                                        ! It seems there is a space then at the end
                                        ! of cutname

write(*,*)  (cutname(1:2) == 'AB')      ! Gives output  T (true)
write(*,*)  (cutname(3:3) == ' ')       ! Gives output  F (false)
write(*,*)  (cutname  == 'AB ')         ! Gives output  F (false)

end function

我很好奇在这种情况下发生了什么。提前致谢。

4

1 回答 1

2

Fortran 中的标准字符串是固定长度的。如果您不使用整个字符串,它们会在末尾用空格/空格填充。

我更改了您的示例程序以通过 gfortran 和 ifort 的编译器检查。您的函数没有返回,因此作为子例程更好。编译器注意到实际参数和虚拟参数的长度之间的不一致——因为我将过程放入模块中并use对其进行了编辑,以便编译器可以检查参数的一致性。他们抱怨将长度为 2 的字符串传递给长度为 10 的字符串。应该如何定义剩余的字符?

module test_mod

contains

subroutine test(name)
implicit none
character(10) :: name
character(3)  :: cutname

write(*,*) '-'//name//'-'             ! Gives output "-AB        -"
                                      ! Space has then been added at the end
cutname(1:3) = name(1:3)
write(*,*) '1-'//cutname//'-'           ! Gives output "-AB -"
                                        ! It seems there is a space then at the end
                                        ! of cutname

write(*,*)  (cutname(1:2) == 'AB')      ! Gives output  T (true)
write(*,*)  (cutname(3:3) == ' ')       ! Gives output  F (false)
write(*,*)  (cutname  == 'AB ')         ! Gives output  F (false)

end subroutine test

end module test_mod



program main
use test_mod
implicit none

call test('AB          ')
end program

当我运行这个版本时,输出是 T、T 和 T,这是我所期望的。

编辑:我建议使用编译器的完整警告和错误检查选项。这就是我快速发现示例问题的方式。使用 gfortran -O2 -fimplicit-none -Wall -Wline-truncation -Wcharacter-truncation -Wsurprising -Waliasing -Wimplicit-interface -Wunused-parameter -fwhole-file -fcheck=all -std=f2008 -pedantic -fbacktrace:.

字符串赋值语句不需要两侧具有相同的长度。如果 RHS 比 LHS 上的字符串变量短,它将在末尾用空格填充。在这里,论点应该是一致的,包括长度。

于 2013-07-12T08:45:18.853 回答