Converting a string to an integer in Fortran 90
28,907
You can read
a string into an integer variable:
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
Author by
Admin
Updated on March 11, 2020Comments
-
Admin about 4 years
I know that
IACHAR(s)
returns the code for the ASCII character in the first character position of the string s, but I need to convert the entire string to an integer. I also have a few number of strings (around 30 strings, each consists of at most 20 characters). Is there any way to convert each one of them to a unique integer in Fortran 90? -
Admin almost 8 years
read(str,*,iostat=stat) int
<- this is the important part of the answer for others like me searching for the same thing. Thanks Alex. Here's some other examples: eng-tips.com/viewthread.cfm?qid=4337 & vikas-ke-funde.blogspot.com/2010/06/… -
Vladimir F Героям слава about 5 yearsYou should disclose that you are an author of the said library. Also, an example of a call of the conversion procedure would be more valuable than just this product advertisment.