How to check if user input fits in variable?

190 views Asked by At

I'm trying to write a simple program to calculate a function with Fortran95/03 which needs as input a number(x) and gets as output a number(y). The user input is a real :: input and the read call looks like

read (*,*, iostat=stat) input
if(stat > 0) then
    print *, "False input, use numbers!"

The iostat helps me to check if the input was a number or a letter.

My problem is that if I enter a very big number, like 1000000000000, the program crashes with the error message "bufferoverflow". I know that I can make the real bigger than a 4 byte variable, but I also can make the input number bigger, so this does not solve the problem.

The main question is, is it possible to prevent the program crashing because of user input?

2

There are 2 answers

0
Vladimir F Героям слава On

Checking the values of the user's input is a very basic technique which must be employed in all kinds of software which interacts with someone else than just the author. It is used in all programming languages.

You can just use a simple condition

if (input > input_max) then
  print *, "Input value too large, try again"
  cycle ! or return stop or set some flag or whatever
end if

Don't forget the value may be also too small!

It is important to understand where does the crash come from. It certainly does not come from just from inputting a large number but using the number in a bad way, for example, allocating an array which is too large or by making a calculation which triggers a floating point exception.

0
IanH On

Read the input as a string, then validate the string input, then use an internal read to convert the validated string into a REAL.

There are many aspects of processor dependent behaviour to input and output, as a general principle if you want robustness then you need to do much of the leg work yourself. For example, if malformed input for a real is provided, then there is no requirement that a processor identify that as an error condition and return a non-zero IOSTAT code.

List directed input offers further challenges, in that it has a number of surprising features that may trip you and your users up.