我想在 FORTRAN 中读取未知边界行中的整数序列。我的问题类似于以下之前的帖子,
Reading a file of lists of integers in Fortran
但是我想在一行中读取一系列未知数的整数并将其保存在单独的数组中。连续的整数行应该保存到其他数组中
My file looks like this
5 7 8 9 10 13 # should be stored f(1)(6) arrays
93 102 92 # c(1)(3)
105 107 110 145 147 112 # f(2)(6)
97 98 # b(1)(2)
12 54 55 # c(2)(3)
15 17 21 23 45 # e(1)(5)
43 47 48 51 62 # d(1)(4)
因此我有一个整数序列,最大长度为 6(存储在 f 数组中),最小长度为 2(存储在 b 数组中)。我有数百行这样的行,因此我需要根据最大长度进行分类并计算它们。
最佳答案
可能有很多方法可以做到这一点,下面就是一个这样的例子。此处,split() 对行中所有值的列表定向输入进行多次试验,直到遇到非数字字符或行尾。
subroutine split( line, vals, n )
implicit none
character(*), intent(in) :: line
real*8 :: vals(*), buf( 100 ) !! currently up to 100 items (for test)
integer :: n
n = 1
do
read( line, *, end=100, err=100 ) buf( 1 : n ) !! (See Appendix for why buf is used here)
vals( 1:n ) = buf( 1:n )
n = n + 1
enddo
100 continue
n = n - 1
end
program main
implicit none
character(200) :: line
real*8 :: vals( 100 )
integer :: n
open( 10, file="test.dat", status="old" )
do
read( 10, "(a)", end=500 ) line
call split( line, vals, n )
if ( n == 0 ) then
print *, "comment line"
else
print *, nint( vals( 1 : n ) )
endif
enddo
500 continue
close( 10 )
end
如果 test.dat 包含问题中的整行,加上以下几行
# additional data
1,2,3 , 4 , 5 # comma-separated integers
1.23e2 -4.56e2 , 777 # integer/floating-point mixed case
它给
comment line
5 7 8 9 10 13
93 102 92
105 107 110 145 147 112
97 98
12 54 55
15 17 21 23 45
43 47 48 51 62
comment line
1 2 3 4 5
123 -456 777
因此,可以通过将 vals(1:n)
中的值复制到所需的数组来保存每一行的结果。
[附录(感谢@francescalus)]
在上面的代码中,数据被一次读入buf(1:n)
,然后复制到vals(1:n)
。人们可能认为将数据读入 vals(1:n)
会更直接,这样
read( line, *, end=100, err=100 ) vals( 1 : n )
但是,不推荐这种直接方法,因为当读取语句遇到“结束”或“错误”条件时,vals(1:n)
变为未定义。尽管 ifort 和 gfortran 似乎保留 vals(1:n)
中的数据,即使满足该条件(因此即使使用直接方法它们也能工作),但不能保证其他编译器具有相同的行为.相反,缓冲区方法通过将数据保存到 vals(1:n)
前一步来避免这种风险,因此未定义的数据不会被使用。这就是为什么在上面的代码中使用缓冲区方法的原因,尽管它比一条语句长。
关于fortran - 在 Fortran 中读取具有未知边界的行中的整数序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32022062/