Reputation: 1297
I am building a basic program in Silverfrost FTN5 wherein I input an integer from user.
If user enters a float value, it throws an error and the program ends. Is there any way I can handle this invalid input and ask user to enter valid input?
Upvotes: 0
Views: 644
Reputation: 29391
There are several methods. 1) Read the input into a string and parse the string. If the string contains a period, reject it and re-ask for input. If the string appears valid, do an "internal" read of the integer from the string: read (string, *) IntVal
. 2) More robust since this gracefully detects all errors: use the IOSTAT=
keyword in your read statement. If the value is non-zero, there was an error ... re-ask for input.
EDIT: Code example:
program TestRead
integer :: number, ReadStatus
write (*, '( "Input integer: " )', advance="no" )
ReadInt: do
read (*, *, iostat=ReadStatus) number
if ( ReadStatus == 0 ) then
exit ReadInt
else
write (*, '( / "READ ERROR: please re-input:" )' )
end if
end do ReadInt
write (*, '( / "Value read: ", I0 )' ) number
end program TestRead
Upvotes: 2