【问题标题】:iostat and inputting from terminaliostat 和从终端输入
【发布时间】:2025-12-22 08:10:12
【问题描述】:

我了解iostat的用法,当我们从终端输入时,如何使状态为io<0,以便程序了解输入结束?

例如在一个简单的代码中求均值:

program mean
implicit none
real :: x
real :: gmean, amean, hmean
real :: summ,pro,invsum
integer :: i, valid
integer :: io, countt

countt=0
valid=0
summ=0
pro=1
invsum=0

do
    read(*,*,iostat=io) x
    if (io<0) exit
    countt=countt+1
    if (io>0) then
        write(*,*) 'error in input..try again !!!'
    else
        write(*,*) 'Input data #.',countt,':',x
        if (x<=0) then
            write(*,*) 'input <=0..ignored !!'
        else
            valid = valid + 1
            summ = summ + x
            pro = pro*x
            invsum = invsum + (1.0/x)
        end if
    end if
end do
if (valid>0) then
    amean=summ / valid
    gmean = pro**(1.0/valid)
    hmean=valid / invsum

    write(*,*) 'number of valid items --->',valid
    write(*,*) 'arithmetic mean --> ',amean
    write(*,*) 'geometric mean --> ',gmean
    write(*,*) 'harmonic mean --> ',hmean
else
    write(*,*) 'no valid inputs !!'
end if
end program mean

当我执行代码时,一切正常,除了它不断要求输入。我不明白如何制作io&lt;0

【问题讨论】:

    标签: io terminal fortran


    【解决方案1】:

    在 Linux 和 MAC OS 等 Unix 系统上,您可以使用 Ctrl-d 表示文件结束。

    在 Windows 上,使用 Ctrl-z(来自 here)。

    Wikipedia article 进一步比较了各种操作系统上的命令行快捷方式。

    【讨论】:

    • @ss1729 只需提供每行条目。文件结束信号是信号,嗯,在文件末尾:)
    【解决方案2】:

    我喜欢对用户好(即使只是我..)

    character*80 input
    real val
    integer stat
    input=''
    do while(input.ne.'e')
     write(*,'(a)',advance='no')'enter val [e to end]: '
     read(*,'(a)',iostat=stat)input !iostat here to catch ^d and such
     if(stat.ne.0)input='e'
     if(input.ne.'e')then
      read(input,*,iostat=stat)val  !check iostat here
                                    !in case user entered some
      if(stat.ne.0)then             !other non-number
       write(*,*)val
      else
       write(*,*)'expected a number'
      endif
     endif
    enddo
    end
    

    【讨论】: