Search code examples
stringiofortrangfortran

How to read numeric data from a string in Fortran


I have a character string array in Fortran as ' results: CI- Energies --- th= 89 ph=120'. How do I extract the characters '120' from the string and store into a real variable?

The string is written in the file 'input.DAT'. I have written the Fortran code as:

implicit real*8(a-h,o-z)
character(39)  line
open(1,file='input.DAT',status='old')
read(1,'(A)') line,phi
write(*,'(A)') line
write(*,*)phi
end

Upon execution it shows:

At line 5 of file string.f (unit = 1, file = 'input.dat')
Fortran runtime error: End of file

I have given '39' as the dimension of the character array as there are 39 characters including 'spaces' in the string upto '120'.


Solution

  • Assuming that the real number you want to read appears after the last equal sign in the string, you can use the SCAN intrinsic function to find that location and then READ the number from the rest of the string, as shown in the following program.

    program xreadnum
        implicit none
        integer :: ipos
        integer, parameter :: nlen = 100
        character (len=nlen) :: str
        real :: xx
        str  = "results: CI- Energies --- th= 89 ph=120"
        ipos = scan(str, "=", back=.true.)
        print*, "reading real variable from '" // trim(str(1+ipos:)) // "'"
        read (str(1+ipos:),*) xx
        print*, "xx = ", xx
    end program xreadnum
    ! gfortran output:
    ! reading real variable from '120'
    ! xx =    120.000000