良工造 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 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗