如何从FORTRAN中的字符串读取数字数据 [英] How to read numeric data from a string in FORTRAN

查看:2608
本文介绍了如何从FORTRAN中的字符串读取数字数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在FORTRAN中有一个字符串数组,结果如下:CI-能量--- th = 89 ph = 120'。如何从字符串中提取字符'120'并存储到实变量中?



字符串写入文件'input.DAT'。我已经写了FORTRAN代码:

$ p code $ implicit real * 8(ah,oz)
character(39)line
open(1,file ='input.DAT',status ='old')
read(1,'(A)')line,phi
write(*,'(A )')line
write(*,*)phi
end

执行它显示:

pre $ 在文件string.f的第5行(单元= 1,file ='input.dat')
Fortran运行时错误:文件结尾

我给出了'39'作为字符数组,因为有39个字符,包括字符串中的'spaces'到'120'。

解决方案

假设真实数字想要读取出现在字符串中最后一个等号后面,可以使用SCAN内部函数来查找该位置,然后从该字符串的其余部分读取数字,如以下程序中所示。

 程序xreadnum 
隐式无
整数:: ipos
integer,parameter :: nlen = 100
character(len = nlen):: str
real :: xx
str =结果:CI- Energies --- th = 89 ph = 120
ipos = scan(str,=,back = .true。)
print *,从真正的变量读取'// trim(str(1 + ipos :) )//'
read(str(1 + ipos:),*)xx
print *,xx =,xx
结束程序xreadnum
! gfortran输出:
!从'120'
阅读真实变量! xx = 120.000000


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

解决方案

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    

这篇关于如何从FORTRAN中的字符串读取数字数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆