我知道IACHAR(s)
在字符串 s 的第一个字符位置返回 ASCII 字符的代码,但我需要将整个字符串转换为整数。我还有一些字符串(大约 30 个字符串,每个字符串最多包含 20 个字符)。有没有办法在 Fortran 90 中将它们中的每一个都转换为唯一的整数?
最佳答案
您可以 read
将字符串转换为整数变量:
module str2int_mod
contains
elemental subroutine str2int(str,int,stat)
implicit none
! Arguments
character(len=*),intent(in) :: str
integer,intent(out) :: int
integer,intent(out) :: stat
read(str,*,iostat=stat) int
end subroutine str2int
end module
program test
use str2int_mod
character(len=20) :: str(3)
integer :: int(3), stat(3)
str(1) = '123' ! Valid integer
str(2) = '-1' ! Also valid
str(3) = 'one' ! invalid
call str2int(str,int,stat)
do i=1,3
if ( stat(i) == 0 ) then
print *,i,int(i)
else
print *,'Conversion of string ',i,' failed!'
endif
enddo
end program
关于string - 在 Fortran 90 中将字符串转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24071722/