Prevent FORTRAN from closing when a character is inputed instead of a number

fortran, gfortran

Solution

You're using list-directed input. The second `*` in the statement `read(*,*)` essentially tells the compiler/run-time system that you will provide it with something at run time that can be interpreted as an `integer`. If you want to give yourself the freedom to make mistakes on input you have (at least) 3 choices.

- You can, as @User7391's answer already says, read the input into a character variable and parse it yourself. That kind user has even offered to write the code for you !

- You could modify the read command to something like `read(*,*,err=1234)` where `1234` is the label of your error-handling statement(s). This approach is now considered rather old-fashioned and might be frowned upon.

- You could modify the read command to something like `read(*,*,iostat=ios)` where `ios` is an integer variable which catches the `iostat` (i/o status flag) reported by the `read` statement. You might then write the line `if (iostat/=0) ...` for error handling. This is considered to be the more up to date approach.

Problem

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!

Original source