Fortran 在 txt 文件中查找字符串
Fortran find string in txt file
我想知道如何在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)
有什么函数可以returns do-while 循环找到的位置吗?找到这个职位的更好方法是什么?
谢谢
下面的程序展示了如何从搜索字符串为第一个单词的行中读取数字。它使用内部读取,这在 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.
我想知道如何在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)
有什么函数可以returns do-while 循环找到的位置吗?找到这个职位的更好方法是什么?
谢谢
下面的程序展示了如何从搜索字符串为第一个单词的行中读取数字。它使用内部读取,这在 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.