scanf
returns the number of inputs read and assigned, not the value of the input itself. In this particular case you are only expecting a single input, so scanf
will return 1 on success, 0 on a matching failure (i.e., the input doesn’t start with a decimal digit), or EOF if it sees end-of-file or an error.
If you want to test against the value of the input, you’d do something like
while( scanf( “%d”, &n ) == 1 && n == EXPECTED_VALUE )
{
printf( “%d”, n );
}
Edit
Actually, a better way to do that would be something like this:
int n;
int itemsRead;
/**
* Read from standard input until we see an end-of-file
* indication.
*/
while( (itemsRead = scanf( "%d", &n )) != EOF )
{
/**
* If itemsRead is 0, that means we had a matching failure;
* the first non-whitespace character in the input stream was
* not a decimal digit character. scanf() doesn't remove non-
* matching characters from the input stream, so we use getchar()
* to read and discard characters until we see the next whitespace
* character.
*/
if ( itemsRead == 0 )
{
printf( "Bad input - clearing out bad characters...\n" );
while ( !isspace( getchar() ) )
// empty loop
;
}
else if ( n == EXPECTED_VALUE )
{
printf( "%d\n", n );
}
}
if ( feof( stdin ) )
{
printf( "Saw EOF on standard input\n" );
}
else
{
printf( "Error while reading from standard input\n" );
}