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:
THE OUTPUT IS:
1234
1234.5678
T
F
1234
1234.5678
T
F
Press any key to exit...
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...

7 Comments:
I love you... The solution is so simple, yet elegant and I have bashed my head on the table for the past two days trying to get this to work until I found this blog
By
Pymp, At
August 10, 2009 4:30 AM
Hi, i've been looking how to use fortran in windows, but force fortran don't let me compile, and when i paste the example, it does'nt work, can you help me?
By
Fabrizzio, At
August 23, 2009 3:36 PM
Officially it's called using internal files.
By
jgdes, At
October 3, 2009 8:44 AM
Wow... I have looked for several hours
now how do do this, and now it works. Thank you very much!
By
Daniel, At
January 16, 2010 6:43 PM
Hi! The "download" link on the right column is old: it takes to an old download page
By
free, At
March 10, 2010 2:56 PM
This comment has been removed by the author.
By
Dan, At
May 23, 2010 7:54 AM
I once used the equivalence command to convert character to integer. I was making a pre-F77 application that passed characters to a subroutine using the old integer method. By taking the integer input, then using equivalence to "put" it in a character variable, I was able to get a program compiled in F77 to use the older subroutine.
Dan
By
Dan, At
May 23, 2010 7:56 AM
Post a Comment
Subscribe to Post Comments [Atom]
<< Home