【问题标题】:Fortran find string in txt fileFortran在txt文件中查找字符串
【发布时间】:2015-03-18 15:06:00
【问题描述】:

我想知道如何在 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 循环找到的位置?找到这个职位的更好方法是什么?

谢谢

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 我是 fortran 新手,不知道如何在 txt 文件中查找字符串。
  • 写好你知道如何写的代码,并清楚地指出(希望是)剩余困难的小区域。 SO 并不是学习 Fortran(或任何其他编程语言)编程基础知识的地方,而且我们很少有人愿意为您编写所有代码。
  • 查看'index'函数
  • 我添加了我的代码。我查找了索引函数,但它在字符串中查找子字符串。但是,我必须在 txt 文件中查找它。一种方法是将我所有的 txt 文件添加到一个字符串中,但这似乎不合理。或者我可以使用 index 函数在 txt 中查找字符串吗?

标签: io fortran


【解决方案1】:

下面的程序显示了如何从搜索字符串为第一个单词的行中读取数字。它使用内部读取,这在 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.

【讨论】:

    猜你喜欢
    • 2018-10-26
    • 1970-01-01
    • 2013-12-23
    • 1970-01-01
    • 2014-05-16
    • 2016-03-14
    • 2021-10-22
    • 2015-04-05
    • 1970-01-01
    相关资源
    最近更新 更多