Pages

Friday, July 31, 2009

Fortran by Fortran: Character to Integer, Float... and vice-versa

Yesterday I received an e-mail with a really tricky problem: How to convert from String (character sequence) to Integer in Fortran?. The first time I were in front of this problem I searched by some intrinsic function and didn't found anything. Then, I made my own function that reads char by char and converts it to the relative Integer value. Some day after, I found another solution to this problem and it was really simple. You can use the READ and WRITE statements to deal with conversions between characters to anything else and vice-versa. Take a look at the codes below.

CONVERTING TO AND FROM CHARACTERS:


program characterconversions

character*50 s
integer i
double precision d
logical t,f

s = '1234'
read (s,*) i

s = '1234.5678'
read (s,*) d

s = 'T' !TRUE
read (s,*) t

s = 'F' !FALSE
read (s,*) f

print *,i
print *,d
print *,t
print *,f

write (s, *) i
print *,s

write (s, *) d
print *,s

write (s, *) t
print *,s

write (s, *) f
print *,s

print '("Press any key to exit... "$)'
read (*,*)

end

THE OUTPUT IS:

1234
1234.5678
T
F
1234
1234.5678
T
F
Press any key to exit...