我想知道如何在txt文件中查找字符串并读取其后的数字。 该文件的txt部分如下:
...
x0 1 0 1 0.5 0
dx0 0 0 1 0 0
这就是我要做的事情:
character :: c
real :: v1(1:5), v2(1:5)
integer :: i
...
open(10, file="input.txt", action="read")
...
read(unit = 10, fmt=*) c
do while(c/='x')
read(unit = 10, fmt=*) c
end do
read(unit = 10, fmt=*) c
read(unit = 10, fmt=*) v1(1), v1(2), v1(3), v1(4), v1(5)
read(unit = 10, fmt=*) c c
read(unit = 10, fmt=*) v2(1), v2(2), v2(3), v2(4), v2(5)
close(10)
是否有任何函数返回do-while循环找到的位置?找到这个职位的更好方法是什么?
由于
答案 0 :(得分:2)
下面的程序显示了如何从搜索字符串是第一个单词的行中读取数字。它使用内部读取,这在Fortran I / O中通常很有用。
program xinternal_read
implicit none
integer :: ierr
integer, parameter :: iu = 20
character (len=*), parameter :: search_str = "dx0"
real :: xx(5)
character (len=1000) :: text
character (len=10) :: word
open (unit=iu,file="foo.txt",action="read")
do
read (iu,"(a)",iostat=ierr) text ! read line into character variable
if (ierr /= 0) exit
read (text,*) word ! read first word of line
if (word == search_str) then ! found search string at beginning of line
read (text,*) word,xx
print*,"xx =",xx
end if
end do
end program xinternal_read
输出
xx = 0. 0. 1. 0. 0.