2017-06-13 126 views
0

我正在學習Fortran,目前正在fortrantutorials.com上進行練習。我必須運行下面的代碼:Fortran文件錯誤結束

program magic  
    implicit none 
    real, dimension(100) :: a,b,c,d 
    open(10, file='data.txt') 
    read(10,*) a 
    b = a*10 
    c = b-a 
    d = 1 
    print*, 'a = ', a 
    print*, 'b = ', b 
    print*, 'c = ', c 
    print*, 'd = ', d 
end program magic 

它讀取以下的data.txt文件:

24 
45 
67 
89 
12 
99 
33 
68 
37 
11 

當我運行它,它顯示了這個錯誤:

At line 6 of file test.f95 (unit = 10, file = 'data.txt') 
Fortran runtime error: End of file 
[Finished in 0.0s with exit code 2] 

6號線指的是以下行,並且我已經雙重檢查'data.txt'和我的fortran文件確實在同一個目錄中:

read(10,*) a 

我能做些什麼來解決這個問題?提前致謝。

+0

data.txt是否有(至少)100行? – francescalus

回答

1
read(10,*) a 

嘗試讀取100個數字,因爲a尺寸爲100

real, dimension(100) :: a 

您的文件不包含100個號碼,所以當它到達文件的末尾崩潰。

只需讀取消息編譯器會告訴你:

"Fortran runtime error: End of file"

1

如果添加IOSTAT=<scalar-int-variable>到您的閱讀,這將設置變量,而不是崩潰:

integer :: IOSTAT 
    CHARACTER*(128) :: IOMSG 
    open(10, file='data.txt') 
    read(10,*,IOSTAT=IOSTAT,IOMSG=IOMSG) a 
    IF (IOSTAT .NE. 0) THEN 
    WRITE(*,*) "WARNING: Read failed with message '", TRIM(IOMSG), "'" 
    END IF 

不信任的結果這種失敗的READ語句。