Research Profile

This dewdrop world, is a dewdrop world, and yet, and yet...

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 the output of program integer2string:

Example 2:
program string2integer
integer :: i
character*10 :: str
str = ' 013 '
read(str,*) i
write(*,'(i2)') i
end program string2integer

Here is the output of program string2integer:

Hope it helps Happy