使用 Fortran 90 在输入文件中正确读取注释行 [英] Reading comment lines correctly in an input file using Fortran 90

查看:24
本文介绍了使用 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

我用

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 不会自动跳过输入文件中的注释行.您可以通过首先将行读入字符串,检查注释符号的第一个字符或搜索该符号的字符串,然后如果该行不是注释,对字符串进行内部读取"以轻松完成此操作获取数值.

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 read_loop
    end if
    if ( index (line, "*") /= 0 )  cycle read_loop
    read (line, *) dat1
end do read_loop

这篇关于使用 Fortran 90 在输入文件中正确读取注释行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆