【问题标题】:Fortran array inputFortran 数组输入
【发布时间】:2020-06-03 00:02:19
【问题描述】:

我已经一年没有做过任何 Fortran 编程了,现在看来我有点生疏了。因此,我不会向您提供我所有失败的尝试,但会谦虚地请您帮助我完成以下工作。 我有以下“输入”文件

1 5 e 4  
A b & 1  
c Z ; b  
y } " N  
t r ' +  

它可以有更多的列和/或行。我现在想将这些 ASCII 字符中的每一个分配给数组 x(i,j),以便在 ICHAR 转换后进一步处理它们。在此示例中,i=1,4,j=1,5,但它可以是任何 No,具体取决于输入文件。最简单的例子

PROGRAM Example
integer :: i, j
CHARACTER, ALLOCATABLE, DIMENSION(:,:) :: A
READ *, A
ALLOCATE (A(i,j))
PRINT *, A
END PROGRAM Example

编译(Example.f95)但是

cat input | ./Example.f95

不提供任何输出。 我将非常感谢有关如何将上述字符串作为数组的 x(i,j) 项导入程序的建议。

【问题讨论】:

    标签: arrays input fortran ascii gfortran


    【解决方案1】:

    在 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)) 格式的原因。当然,当你的角色不是从行中的第一个位置开始时,这会搞砸。

    【讨论】:

    • 如果一行中有超过 1024 个字符会怎样?我的代码允许任意行长。您也不需要猜测行数。您只需阅读文件即可计算行数(请参阅我的答案),然后倒带以进行实际阅读。您甚至对动态调整大小的复杂程度发表了评论。
    • 如果一行中有超过 1024 个字符会怎样?我的代码允许任意行长。您也不需要猜测行数。您只需阅读文件即可计算行数(请参阅我的答案),然后倒带以进行实际阅读。您甚至对动态调整大小的复杂程度发表了评论。
    • 首先,您不能倒带标准输入。其次,从硬盘倒带和读取文件两次比读取一次要慢得多。现实世界的数据会以某种方式受到限制。如果您偶尔有 1000 列,请将 line 设为 2000 个字符。
    • 啊,我没注意到你读的是标准输入。在现代硬件和现代操作系统上,它并不慢。
    • 您将read(*, ...) 作为您的第一个阅读声明。您正在从标准输入读取。你认为cat input | 在做什么?哦,是的,stdin 是标准输入的 C 或 UNIX 或 Linux 术语。
    【解决方案2】:

    您需要阅读第一行并确定该行中的字符。然后读取整个文件以确定行数。分配二维数组来保存字符。然后读取文件并将每一行解析为二维数组。有更优雅的方法可以做到这一点,但你去吧

      program foo
    
      implicit none
    
      character(len=:), allocatable :: s
      character, allocatable :: a(:,:)
      integer fd, i, j, n, nr, nc
      !
      ! Open file for reading
      !
      open(newunit=fd, file='tmp.dat', status='old', err=9)
      !
      ! Determine number of characters in a row.  Assumes all rows
      ! are of the same length.
      !
      n = 128
    1 if (allocated(s)) then
         deallocate(s)
         n = 2 * n
      end if
      allocate(character(len=n) :: s)
      read(fd,'(A)') s
      if (len_trim(s) == 128) goto 1
      s = adjustl(s)
      n = len_trim(s)
      deallocate(s)
      !
      ! Allocate a string of the correct length.
      ! 
      allocate(character(len=n) :: s)
      !
      ! Count the number of rows
      !
      rewind(fd)
      nr = 0
      do
         read(fd,*,end=2)
         nr = nr + 1
      end do
      !
      ! Read file and store individual characters in a(:,:)
      !
    2 rewind(fd)
      nc = n / 2 + 1
      allocate(a(nr,nc))
      do i = 1, nr
         read(fd,'(A)') s
         do j = 1, nc
            a(i,j) = s(2*j-1:2*j-1)
         end do
      end do
      close(fd)
      write(s,'(I0)') nc
      s = '('  // trim(s) // '(A,1X))'
      do i = 1, nr
         write(*,s) a(i,:)
      end do
      stop
    9 write(*,'(A)') 'Error: cannot open tmp.dat'
      end program foo
    

    显然,GOTO 在这里是详细的。这是一个优雅的解决方案。

      program foo
    
      implicit none
    
      character, allocatable :: s(:), a(:,:)
      integer fd, i, j, n, nr, nc
    
      ! Open file for reading
      open(newunit=fd, file='tmp.dat', status='old', access='stream', err=9)
    
      inquire(fd, size = n) ! Determine file size.
      allocate(s(n))        ! Allocate space
      read(fd) s            ! Read the entire file
    
      close(fd)
    
      nr = count(ichar(s) == 10)             ! Number of rows
      nc = (count(ichar(s) /= 32) - nr) / nr ! Number of columns 
    
      a = reshape(pack(s, ichar(s) /= 32 .and. ichar(s) /= 10), [nc,nr])
      a = transpose(a)
    
      do i = 1, nr
         do j = 1, nc
            write(*,'(A,1X)',advance='no') a(i,j)
         end do
         write(*,*)
      end do
      stop
    9 write(*,'(A)') 'Error: cannot open tmp.dat'
      end program foo
    

    【讨论】:

    • 没有goto,您没有找到方法吗?例如do - exit 循环?还是 do while 循环?
    • 我确实指出可能有更优雅的方法来解决问题。更重要的是,我不会对GOTO 的明智使用感到困惑。如果有什么你应该注意到REWIND(FD) 应该出现在GOTO 括起来的代码区域内。我让你考虑一下。
    • 我其实很喜欢你的第二个解决方案。在我看来,将输入文件作为流读取是个好主意。
    • 它仍然存在缺陷,因为它假设行以 LF 结尾。 Windows 使用(曾经使用过?)CRLF。需要检查字符串。
    猜你喜欢
    • 2023-03-27
    • 1970-01-01
    • 2023-02-03
    • 2016-11-09
    • 2015-10-22
    • 2014-08-01
    • 2014-02-19
    • 1970-01-01
    • 2021-07-01
    相关资源
    最近更新 更多