使用Fortran 90在输入文件中正确读取注释行 [英] Reading comment lines correctly in an input file using Fortran 90
问题描述
据我的理解,Fortran在从文件读取数据时,将跳过以星号(*)开头的行,假设它们是注释。好吧,我似乎有一个问题,实现这个行为,我创建了一个非常简单的程序。这是我简单的Fortran程序:
It is my understanding that Fortran, when reading data from file, will skip lines starting with and asterisk (*) assuming that they are a comment. Well, I seem to be having a problem with achieving this behavior with a very simple program I created. This is my simple Fortran program:
1 program test
2
3 integer dat1
4
5 open(unit=1,file="file.inp")
6
7 read(1,*) dat1
8
9
10 end program test
这是file.inp:
This is "file.inp":
1 *Hello
2 1
$ b b
我用
I built my simple program with
gfortran -g -o test test.f90
运行时出现错误:
At line 7 of file test.f90 (unit = 1, file = 'file.inp')
Fortran runtime error: Bad integer for item 1 in list input
当我运行删除注释行的输入文件,即:
When I run the input file with the comment line deleted, i.e.:
1 1
代码运行正常。所以似乎是一个问题,Fortran正确解释的注释行。
The code runs fine. So it seems to be a problem with Fortran correctly interpreting that comment line. It must be something exceedingly simple I'm missing here, but I can't turn up anything on google.
推荐答案
Fortran doesn不会自动跳过输入文件中的注释行。你可以很容易地做到这一点,首先读取行到一个字符串,检查第一个字符的注释符号或搜索字符串的那个符号,然后如果该行不是一个注释,做一个内部读取字符串
Fortran doesn't automatically skip comments lines in input files. You can do this easily enough by first reading the line into a string, checking the first character for your comment symbol or search the string for that symbol, then if the line is not a comment, doing an "internal read" of the string to obtain the numeric value.
类似于:
use, intrinsic :: iso_fortran_env
character (len=200) :: line
integer :: dat1, RetCode
read_loop: do
read (1, '(A)', isostat=RetCode) line
if ( RetCode == iostat_end) exit ReadLoop
if ( RetCode /= 0 ) then
... read error
exit ReadLoop
end if
if ( index (line, "*") /= 0 ) cycle read_loop
read (line, *) dat1
end do read_loop
这篇关于使用Fortran 90在输入文件中正确读取注释行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!