Fortran

Guide To Learn

How can I convert a string to an integer and other types? What about the reverse?

A: Use an “internal read” or “internal write”. In effect, you use a character variable as the file name and read or write the I/O list. You write things like

   read (character_variable, format) list of variables

to convert a string to another type and

   write (character_variable, format) list of variables

to convert to a string from another type, as demonstrated by the following program:

program xconvert_integer_string   
character(20) :: cnum 
integer       :: i 
i = 445 
write(cnum,'(i5)') i 
write(*,'(a)') trim(cnum) ! should output "  445" 
write(cnum,'(i5.5)') i 
write(*,'(a)') trim(cnum) ! should output "00445" 
i = 34 
write(cnum,'(i0)') i 
write(*,'(a)') trim(cnum) ! should output "34" 
end program xconvert_integer_string

This answer is based on messages in comp.lang.fortran by Paul van Delst and Dick Hendrickson.

How can I convert a string to an integer and other types? What about the reverse?

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top