Fortran数组输入

问题描述 投票:0回答:1

我一年没有做任何Fortran编程,现在看来我很生锈。因此,我不会为您提供所有失败的尝试,但会虚心请您在以下方面提供帮助。我有以下“输入”文件1 5 e 4A b & 1c Z ; by } " Nt r ' +它可以具有更多的列和/或行。现在,我想将每个ASCII字符分配给数组x(i,j),以便在进行ICHAR转换后可以进一步处理它们。在此示例中,i = 1,4,j = 1,5,但是根据输入文件的不同,它可以是任何No。最简单的例子PROGRAM Exampleinteger :: i, jCHARACTER, ALLOCATABLE, DIMENSION(:,:) :: AREAD *, AALLOCATE (A(i,j))PRINT *, AEND PROGRAM Example编译(Example.f95)但cat input | ./Example.f95没有给出任何输出。我将不胜感激有关如何将上述字符串作为数组的x(i,j)项导入程序的建议。

arrays input fortran ascii gfortran
1个回答
0
投票

您需要阅读第一行,并确定该行中的字符。然后读取整个文件以确定行数。分配2D数组以容纳字符。然后读取文件并将每一行解析为2D数组。有更优雅的方法可以执行此操作,但是您可以在这里

  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
© www.soinside.com 2019 - 2024. All rights reserved.