Research Profile

Seek and you shall find...

FORTRAN Tip: Convert a String to Other Types

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:
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!