Reputation: 159
I understand the use of iostat
, when we are inputting from terminal how do I make the status io<0
so that the program understands the end of input is reached?
For example in a simple code to find mean:
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
When I execute the code everything works fine except it keeps on asking for inputs. I do not understand how to make io<0
.
Upvotes: 1
Views: 82
Reputation: 6999
I like to be nice to the user (even if its just me..)
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
Upvotes: 1
Reputation: 18118
On Unix systems such as Linux and MAC OS, you can use Ctrl-d to signal the end of the file.
On Windows, use Ctrl-z (from here).
This Wikipedia article compares further command line shortcuts on the various operating systems.
Upvotes: 1