Fortran读取语句的iostat参数返回代码5001

问题描述

我正在fortran中编写一个计算BMI的小代码,但是read语句的iostat参数有一个问题。整个代码如下:

program calculate_bmi
  ! Simple BMI calculator
  implicit none
  character :: unit_system
  character :: height_unit*15,weight_unit*10
  real :: height,weight,bmi
  integer :: ierror


  print *,'Would you like to use imperial or metric system?'
  systemloop: do
    print *,'Press [I] for imperal system or press [M] for metric system.'
    read *,unit_system
    if (unit_system == 'i' .or. unit_system == 'I' .or. &
     unit_system == 'm' .or. unit_system == 'M') exit systemloop
  end do systemloop

  if (unit_system == 'i' .or. unit_system == 'I') then
    height_unit='inches'
    weight_unit = 'pounds'
  else
    height_unit = 'centimeters'
    weight_unit= 'kilograms'
  end if

  print *,'Type in your height in ',height_unit
  read (*,iostat = ierror) height
  if (ierror /= 0) then
    print *,'Invalid input for height!'
    call exit
  end if
  print *,'Type in your weight in ',weight_unit
  read (*,iostat = ierror) weight
  if (ierror /= 0) then
    print *,'Invalid input for weight!'
    call exit
  end if

  if (unit_system == 'i' .or. unit_system == 'I') then
    bmi = 703 * weight / (height**2)
  else
    bmi = weight / ((height/100)**2)
  end if

  print *,'Your BMI is: '
  write (*,1) NINT(bmi*10)/10.0
  1 format(f6.1)
end program calculate_bmi

此代码块出现问题:

 print *,'Invalid input for weight!'
    call exit
  end if

iostat始终以代码形式返回5001,而read语句不等待输入,而只是终止程序。我做了一些Google-ing,但无法真正弄清楚到底是什么问题。如果我从read语句中删除iostat,则代码可以正常工作,但是在那种情况下,我无法进行错误处理和防止输入错误。

我对FORTRAN有点陌生,所以请让我知道我在哪里犯了错误。另外,我正在使用Gfortran作为编译器。

解决方法

read语句通常需要两个位置参数,一个用于输入单元(或将*声明为标准输入),另一个用于格式(或再次使用*自行解决)。

没有括号,即带有

read *,some_var

该命令自动默认为标准输入流,因此单个*仅用于格式。但是一旦使用括号,就需要声明输入单元和格式。

read语句以及openclosewrite暂时支持iomsg参数,这是一个字符串,并给出易于理解的错误解释。

尝试像这样修改它:

character(len=100) :: ioerrmsg
...
read (*,*,iostat=ioerror,iomsg=ioerrmsg) weight
if (ioerror /= 0) then
    print *,"Encountered Error:"
    print *,ioerrmsg
    call exit
end if

这应该为您提供一些提示。

欢呼

PS:如果有人知道iomsg字符串的默认长度,请在评论中告诉我。但是长度100通常适合我。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...