1

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'.

BM_fortran
  • 23
  • 1
  • 4
  • there are several issues with this code. to fix this particular error replace `read(1,'(A)') line,phi` with two lines: `read(1,'(A)') line` and `read(line(37:),'(F3.0)') phi` . – Andrey Jul 15 '14 at 16:48
  • 5
    Your question suggests that you are relatively new to Fortran programming. Don't learn to use implicit typing, learn to use `implicit none`. – High Performance Mark Jul 15 '14 at 17:04

2 Answers2

3

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
rigel
  • 485
  • 1
  • 6
  • 12
Fortranner
  • 2,525
  • 2
  • 22
  • 25
1

To convert string s into a real type variable r:

READ(s, "(Fw.d)") r

Here w is the total field width and d is the number of digits after the decimal point. If there is no decimal point in the input string, values of w and d might affect the result, e.g.

s = '120'
READ(s, "(F3.0)") r ! r <-- 120.0
READ(s, "(F3.1)") r ! r <--  12.0

Answer to another part of the question (how to extract substring with particular number to convert) strongly depends on the format of the input strings, e.g. if all the strings are formed by fixed-width fields, it's possible to skip irrelevant part of the string:

s = 'a=120'
READ(s(3:), "(F3.0)") r
Andrey
  • 2,503
  • 3
  • 30
  • 39