在Fortran中逐行读取以逗号分隔的文本文件 [英] Reading a comma-delimited text file line-by-line in Fortran
问题描述
1.23,4.56 ,7.89
11,13,Sally
我将这个文本文件保存在我的当前目录。然后,我创建了一个包含以下代码的文件 test.f90 (也保存在当前目录中):
PROGRAM测试
IMPLICIT NONE
REAL :: x,y,z
INTEGER :: m,n
字符首* 20
OPEN(UNIT = 7,FILE =data.txt)
READ(7,*)x,y,z
READ(7,*)m,n,first
PRINT *,x
PRINT *,y
PRINT *,z
PRINT *,m
PRINT *,n
PRINT *,首先
END PROGRAM测试
我使用的是GNU Fortran编译器,我认为它包含功能至少达到并包括Fortran95。上面的代码似乎编译好,至少使用默认设置)。但是,当我运行生成的可执行文件时,出现以下错误消息:
在文件test.f90的第10行(单元= 7 ,file ='data.txt')
Fortran运行时错误:文件结尾
行10是 READ(7,*)m,n,first 行。你能帮我看看我在做什么错了吗?
正确的输出。我在Windows上使用gfortran,并使用记事本创建数据文件。如果用行尾字符(按Enter键)终止第二条数据行,程序将显示正确的输出;如果你没有终止它,它会在执行过程中显示错误。
基本上,运行时试图读取一行,但遇到文件结束符在它到达线的末尾之前。
I am a Fortran novice. I would like to be able to read a text file and save its contents in individual variables. I found a very helpful Fortran tutorial (http://www.math.hawaii.edu/~hile/fortran/fort7.htm#read), and I am trying to follow one of the examples listed there. Specifically, I made a text file called data.txt with the following text:
1.23, 4.56, 7.89
11, 13, "Sally"
I have saved this text file in my current directory. Then, I have created a file test.f90 (also saving it in my current directory) containing the following code:
PROGRAM test
IMPLICIT NONE
REAL :: x, y, z
INTEGER :: m, n
CHARACTER first*20
OPEN(UNIT = 7, FILE = "data.txt")
READ(7,*) x, y, z
READ(7,*) m, n, first
PRINT *, x
PRINT *, y
PRINT *, z
PRINT *, m
PRINT *, n
PRINT *, first
END PROGRAM test
I am using the GNU Fortran compiler, which I think includes the features at least up to and including Fortran95. The above code appears to compile okay, at least with the default settings). But when I run the resulting executable, I get this error message:
At line 10 of file test.f90 (unit = 7, file = 'data.txt')
Fortran runtime error: End of file
Line 10 is the line READ(7,*) m, n, first. Can you please help me see what I am doing wrong in the above code?
I can reproduce both your exact error message and the correct output. I'm using gfortran on Windows, and Notepad to create the data file.
If you terminate the second data line with an end-of-line character (by hitting the Enter key), the program will show the correct output; if you don't terminate it, it will display the error during execution.
Basically, the runtime tries to read a line, but encounters an end-of-file character before it reaches the end of the line.
这篇关于在Fortran中逐行读取以逗号分隔的文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!