在 Fortran 中,最好提前知道您的数组需要多大。我知道在你的情况下你不知道。
假设您的输入至少格式正确(即列匹配并且它们之间只有一个空格),我创建了一个理论上应该能够以任意形状读取它们的代码。 (不是很随意,它假设列数少于 511。)
它使用两种方式:
- 它只是一次读取第一行(1024 个字符,因此列数限制为 511),然后根据长度计算列数
- 然后它分配一个带有猜测行数的数组,一旦发现猜测太小,它就会创建一个行数翻倍的新分配。然后它使用
move_alloc 命令交换分配。
要找到应该结束读取值的时间,它只需检查read 是否返回IOSTAT_END 错误代码。
代码如下:
program read_input
use iso_fortran_env, only: IOSTAT_END
implicit none
character, dimension(:,:), allocatable :: A, A_tmp
character(len=1024) :: line ! Assumes that there are never more than 500 or so columns
integer :: i, ncol, nrow, nrow_guess
integer :: ios
character :: iom
! First, read the first line, to see how many columns there are
read(*, '(A)', iostat=ios, iomsg=iom) line
call iocheck('read first line', ios, iom)
ncol = (len_trim(line) + 1) / 2
! Let's first allocate memory for two rows, we can make it more later.
nrow_guess = 2
allocate(A(ncol, nrow_guess))
! Instead of standard input, we're reading from the line we read before.
read(line, '(*(A1,X))', iostat=ios, iomsg=iom) A(:, 1)
call iocheck('read first line into vals', ios, iom)
! Now loop over all the rows
nrow = 1
read_loop: do
if (nrow >= nrow_guess) then ! We have guessed too small.
! This is a bit convoluted, but the best
! way to increase the array shape.
nrow_guess = nrow_guess * 2
allocate(A_tmp(ncol, nrow_guess))
A_tmp(:, 1:nrow_guess/2) = A(:,:)
call move_alloc(A_tmp, A)
end if
read(*, '(*(A1,X))', iostat = ios, iomsg=iom) A(:, nrow+1)
if (ios == IOSTAT_END) exit read_loop ! We're done reading.
call iocheck('read line into vals', ios, iom)
nrow = nrow + 1
end do read_loop
! The last guess was probably too large,
! let's move it to an array of the correct size.
if (nrow < nrow_guess) then
allocate(A_tmp(ncol, nrow))
A_tmp(:,:) = A(:, 1:nrow)
call move_alloc(A_tmp, A)
end if
! To show we have all values, print them out.
do i = 1, nrow
print '(*(X,A))', A(:, i)
end do
contains
! This is a subroutine to check for IO Errors
subroutine iocheck(op, ios, iom)
character(len=*), intent(in) :: op, iom
integer, intent(in) :: ios
if (ios == 0) return
print *, "IO ERROR"
print *, "Operation: ", op
print *, "Message: ", iom
end subroutine iocheck
end program read_input
编辑添加
我在您的示例输入文件中遇到了特殊字符问题,否则我只会创建一个read(*, *) A(:, nrow)——但这会弄乱特殊字符。这就是我选择显式(*(A1, X)) 格式的原因。当然,当你的角色不是从行中的第一个位置开始时,这会搞砸。