I have a read statement that expects a number, very simple example code:
program test
integer var
read(*,*) var
end
The thing is that I usually input a string of characters (ie: yes) on account of being distracted. How can I prevent my code from halting entirely and instead display an error message of the type You’ve entered an incorrect value. Try again?
I’m thinking something like:
program test
integer var
10 read(*,*) var
if (var.not.a.number) then
write(*,*)'You've entered an incorrect value. Try again'
goto 10
endif
end
What would that var.not.a.number condition look like?
I use gfortran to compile under Ubuntu.
Edit: Thank you all! I ended up implementing HPM’s 3rd option since it was the simplest one:
program test
integer var,iostat,ios
10 read(*,*,iostat=ios) var
if (ios.ne.0) then
write(*,*)'You've entered an incorrect value. Try again'
goto 10
endif
end
Special thanks to User7391 who took the effort to write all that code!
You’re using list-directed input. The second
*in the statementread(*,*)essentially tells the compiler/run-time system that you will provide it with something at run time that can be interpreted as aninteger. If you want to give yourself the freedom to make mistakes on input you have (at least) 3 choices.read(*,*,err=1234)where1234is the label of your error-handling statement(s). This approach is now considered rather old-fashioned and might be frowned upon.read(*,*,iostat=ios)whereiosis an integer variable which catches theiostat(i/o status flag) reported by thereadstatement. You might then write the lineif (iostat/=0) ...for error handling. This is considered to be the more up to date approach.