Wednesday 9 November 2011

Waiting for Correct Input in C programming

Waiting for Correct Input

Sometimes the program stops working because it is waiting for correct input from some source. This problem
can manifest itself in several ways. The simplest way is if your program is waiting for information from the
user, but you have forgotten to have it print a prompt of some sort. The program is waiting for input, but
the user does not know this; the program appears to have locked up. This problem can also manifest itself
in a slightly more insidious fashion due to buffering of output. This topic is discussed in more depth in FAQ
XVII.1.

However, consider the following code fragment:
/*
* This program reads all the numbers from a file,
* sums them, and prints them.
*/
#include <stdio.h>
main()
{
FILE *in = fopen( “numbers.dat” , “r” );
int total = 0 , n;
while( fscanf( in , “ %d” , &n ) != EOF )
{
total += n;
}
printf( “The total is %d\n” , total );
fclose( in );
}

This program will work perfectly well, and quickly, as long as the file NUMBERS.DAT contains integer
numbers—and only integer numbers. If the file contains anything that is not a valid integer value, the
behavior of the program will be curious. When it reaches the flawed value, it will see that the value is not an
integer. It will not read the value; instead it will return an error code. However, the program hasn’t reached
the end of file yet, so the comparison to EOF will not be true. Therefore, the loop executes, with some undefined value for n, and tries to read from the file again. And it finds the same erroneous data there.

Remember, it didn’t read in the data, because it was incorrect. The program will cycle endlessly, forever trying
to read in the bad data. This problem could be solved by having the while loop also test whether correct data
has been read.

Of course, there are many other possible reasons that a program might hang or otherwise appear to freeze;
however, generally, the cause will be in one of these three categories.

Cross Reference:

XI.2: How can I detect memory leaks?

No comments:

Post a Comment