良工造 2021-11-18 19:02 采纳率: 100%
浏览 27
已结题

这个fortran问题是怎么设计的

img

  • 写回答

1条回答 默认 最新

  • 技术专家团-Joel 2021-11-18 20:16
    关注

    这应该是fortran一行一行读入文件时的时候,错误数值比如说文件中本来需要读入数字的地方放进了字符,比如文件a.txt里面有如下内容

    1
    2
    4
    abc
    6
    7
    

    这里abc字符串就是错误的数据,然后打开文件和读入数据都要根据状态量来确定是读入错误还是正确还是到了文件末尾

    program main
    implicit none
    integer(4):: n     ! each line the number to read
    integer(4):: nLine ! which line of the file
    integer(4):: iost1 ! file io state
    integer(4):: iost2 ! file read state
    character(len=100):: open_error_message ! the error message when opening a file
    character(len=100):: read_error_message ! the error message when reading data
    open_error_message = '文件打开错误'
    read_error_message = '数据读入错误'
    open(10, file='a.txt', status='old', action='read', iostat=iost1)
    if(iost1.ne.0) then
        write(*,1000)open_error_message, iost1
    1000 format(T1, A20,'IOSTAT=',I2)
    else ! if read file successfully
        nLine = 0
        do
            read(10,*, iostat=iost2) n
        nLine = nLine + 1
        if(iost2.eq.0) then ! iost2=0时正常读入
            write(*,1001) nLine, n
            1001 format(T1,'From Line ', I2, ' read number', I10)
        elseif(iost2.gt.0)then ! 当数据读入错误时显示错误行号
            write(*,1002) nLine, read_error_message
            1002 format(T1,'Error In Line ',I2,' of the file:', A20)
            continue ! 并且继续读下一行
        elseif(iost2.lt.0)then ! 到了文件末尾就退出循环
            exit
        endif
        enddo
        close(10)!关闭文件
    endif
    end
    

    这个例子的结果:

    From Line  1 read number         1
    From Line  2 read number         2
    From Line  3 read number         4
    Error In Line  4 of the file:数据读入错误
    From Line  5 read number         6
    From Line  6 read number         7
    

    可见第四行数据格式有问题,就出现错误了,但不妨碍其他行的读入
    如有帮助,还望题主给个宝贵的采纳支持答主答题哟,谢谢啦

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 11月26日
  • 已采纳回答 11月18日
  • 创建了问题 11月18日

悬赏问题

  • ¥15 Stata链式中介效应代码修改
  • ¥15 latex投稿显示click download
  • ¥15 请问读取环境变量文件失败是什么原因?
  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错