Search code examples
fortranfortran77

Read lines in Fortran 77 and cast strings to numbers


I have a text file which looks like this:

7000
1.54
-0.32

What I'd like to do is to read from file, line by line, and assign each of the numbers to a numerical variable. There are always 3 lines with numbers, but I don't know the length of numbers. They may be integer, float, negative. How can I achieve this?

And for the Fortran 77. Yeah, I know. But it's not my call to use it.


Solution

  • This is for reading in your file:

    integer :: i
    real    :: a, b
    
    open( file='filename.txt', unit=1234, status='old' )
    read(1234,*) i
    read(1234,*) a
    read(1234,*) b
    close(1234)
    

    And this is for casting a string to real using internal I/O:

    character(len=10) :: str = '1.23e1'
    real    :: a
    
    read(str,*) a