Fortran Coder

标题: 关于二维数组读入,这个错误原因是什么? [打印本页]

作者: likm1110    时间: 2015-3-13 17:31
标题: 关于二维数组读入,这个错误原因是什么?
[Fortran] 纯文本查看 复制代码
Program t
  Implicit None
  Integer, Parameter :: row = 3
  Integer, Parameter :: col = 4
  Real :: a(1:row,1:col)   
  Integer :: i,j  
  Open(11,file='in.txt')
   Do i = 1,row
    Do j = 1,col
      a(i,j) = 10*i+j
      Write(11,*) a(i,j)
    Enddo
  Enddo
  ! read the array==============================================
  Do i = 1,row
    Do j = 1,col
      Read(11,*) a(i,1)
    Enddo
  Enddo
  Close(11)
End Program t

我甚至直接读入刚写进去的数组,编译通过,执行错误报错如下:
“At line 17 of file testofarray01.f95 (unit = 11, file = 'in.txt')
Fortran runtime error: End of file”


作者: li913    时间: 2015-3-13 18:00
end-of-file 错误:
http://fcode.cn/guide-36-2.html
作者: fcode    时间: 2015-3-13 18:04
[Fortran] 纯文本查看 复制代码
Program t
  Implicit None
  Integer, Parameter :: row = 3
  Integer, Parameter :: col = 4
  Real :: a(1:row,1:col)   
  Integer :: i,j  
  Open(11,file='in.txt')
   Do i = 1,row
    Do j = 1,col
      a(i,j) = 10*i+j
      Write(11,*) a(i,j)
    Enddo
  Enddo
  Rewind(11) !// 增加这句
  ! read the array==============================================
  Do i = 1,row
    Do j = 1,col
      Read(11,*) a(i,1)
    Enddo
  Enddo
  Close(11)
End Program t


当你对 11 号文件写入后,文件操作位置就在文件的最末端,此时你再读取,后面没有数据,所以会出错。

你可以把文件操作位置重新设置为文件开始。用 Rewind 语句。

也可以关闭文件,然后重新读取。

(一般情况下,同一次 Open Close,不要即读又写,比较容易出错)
作者: likm1110    时间: 2015-3-13 18:29
fcode 发表于 2015-3-13 18:04
Program t
  Implicit None
  Integer, Parameter :: row = 3

[Fortran] 纯文本查看 复制代码
Program t
  Implicit None
  Integer, Parameter :: row = 3
  Integer, Parameter :: col = 4
  Real :: a(1:row,1:col)
  Integer :: i,j
  Open(11,file='in.txt')
  Do i = 1,row
    Do j = 1,col
      Read(11,*) a(i,j)
      Write(*,*) a(i,j)
    Enddo
  Enddo
  Close(11)
End Program t
谢啦!我以后注意这个问题。还有一个错误,就是如果'in.txt'写成如下形式,也会报错,这是为什么?
11 12 13 14
21 22 23 24
31 32 33 34
执行后

执行结果.PNG (3.77 KB, 下载次数: 397)

执行结果

执行结果

作者: fcode    时间: 2015-3-13 18:47
因为你执行了 12 次循环,所以需要12行。

如无特别声明,每个 read 读一行。如果你只有 3 行,可以这样读:

[Fortran] 纯文本查看 复制代码
Program t
  Implicit None
  Integer, Parameter :: row = 3
  Integer, Parameter :: col = 4
  Real :: a(1:row,1:col)
  Integer :: i,j
  Open(11,file='in.txt')
  Do i = 1,row
      Read(11,*) a(i,:)
      Write(*,*) a(i,:)
  Enddo
  Close(11)
End Program t


更多的二维数组与文本文件行列问题,请阅读:
http://fcode.cn/guide-45-1.html
作者: likm1110    时间: 2015-3-13 21:55
fcode 发表于 2015-3-13 18:47
因为你执行了 12 次循环,所以需要12行。

如无特别声明,每个 read 读一行。如果你只有 3 行,可以这样读 ...

我好好研究一下。感谢!




欢迎光临 Fortran Coder (http://bbs.fcode.cn/) Powered by Discuz! X3.2