Programming With Integers - Input Errors

Chapter chap2 section 9

When you write a program that takes input from human beings, you ought to consider the possibility of the human being pressing the wrong key. At this stage in our study of the C programming language we do not know enough to include comprehensive checks and precautions in our programs and, anyway, such checks would completely obscure the simple purpose of the programs.

However it is worth knowing what happens when the user does make a typing error. The behaviour of scanf() is very simple and fairly well-defined, in the presence of invalid input it simply gives up its attempt to convert from external to internal form. The following sample dialogue, using the basic sum of two numbers program demonstrates what happens. The program was called sum and was run on a SUN Sparc Station. $ is the Unix operating system prompt.

$ sum
Enter x 3
Enter y two
The sum of x and y was 35
$ sum
Enter x one
Enter y The sum of x and y was 32
$ sum
Enter x 1.25
Enter y The sum of x and y was 33
In the first example, the first number (x) was read in satisfactorially but scanf() was unable to process the second input value so gave up without altering the value of the variable "y", which seems to have been 32. See earlier example.

The second example is rather more interesting. When scanf() failed to convert the input one from external decimal to internal binary it left the characters "o", "n" and "e" waiting to be processed. The second call to scanf(), after the second input prompt, found these characters waiting to be processed and also failed to convert them, it never got round to getting any more input from the user. This failure to get more user input is the reason that the program result appears on the same line as the second input prompt, the user never got a chance to type anything, in particular the RETURN at the end of his line of input.

In computer jargon we might say that scanf() doesn't flush the input buffer.

The third example shows the same sort of behaviour as the second example. When scanf() attempts a %d conversion it does not expect to find a decimal point in the input and gives up as soon as it finds the decimal point.


Input Layout