How to read numeric data from a string in FORTRAN

断了今生、忘了曾经 提交于 2019-12-11 04:52:54

问题


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


回答1:


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    



回答2:


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


来源:https://stackoverflow.com/questions/24761661/how-to-read-numeric-data-from-a-string-in-fortran

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!