FORTRAN Tip: Convert a String to Other Types
16/02/2010 23:41
How to convert a string to other types (and vice versa) in FORTRAN?
When I was making the DOSCAR tool, I had to convert some data from integer to string. I found that the easiest way is using a character variable as the file name and read or write the I/O list.
Convert a string to another type
read (character_variable, format) list of variables
Convert to a string from another type
write (character_variable, format) list of variables
Example 1:
Here is output of the integer2string program:
Example 2:
Here is output of the string2integer program:
Hope it helps!
When I was making the DOSCAR tool, I had to convert some data from integer to string. I found that the easiest way is using a character variable as the file name and read or write the I/O list.
Convert a string to another type
read (character_variable, format) list of variables
Convert to a string from another type
write (character_variable, format) list of variables
Example 1:
program integer2string
integer :: i
character*10 :: str
i = 13
write(str,'(i0)') i
write(*,'(a)') trim(str)
write(str,'(i4)') i
write(*,'(a)') trim(str)
write(str,'(i4.4)') i
write(*,'(a)') trim(str)
end program integer2string
Here is output of the integer2string program:
13
13
0013
Example 2:
program string2integer
integer :: i
character*10 :: str
str = ' 013 '
read(str,*) i
write(*,'(i2)') i
end program string2integer
Here is output of the string2integer program:
13
Hope it helps!