Like Stoned_Coder said
scanf returns a lot of potential status results which you have to consider, and take action on each one.
The fgets() approach has the following advantages
1. it separates the EOF test from the conversion results, so your test of the success of sscanf() only has to worry about success/fail of the conversion.
2. if you don't like the buffer, fgets() will have already read upto the next \n, so the input stream is always tidy. You just re-use the buffer in the next fgets() call.
3. you can have several attempts at deciding what a buffer means, should it be necessary (eg. enter a number, or 'q' to quit).
4. when it comes to reading in strings using %s, it becomes more tricky to prevent accidental buffer overflow possibilities.
Some code
Code:
#include <stdio.h>
void use_scanf ( ) {
int i, res;
printf( "Enter number\n" );
res = scanf( "%d", &i );
if ( res == 1 ) {
// success
printf( "Congrats, you entered %d\n", i );
} else
if ( res == 0 ) {
// failed, purge input
// this should also check for EOF
printf( "Junking bad input\n" );
while ( getchar() != '\n' );
} else {
// EOF to start with
printf( "Found EOF\n" );
}
}
void use_fgets ( ) {
char buff[BUFSIZ];
int i, res;
printf( "Enter number\n" );
if ( fgets( buff, BUFSIZ, stdin ) != NULL ) {
res = sscanf( buff, "%d", &i );
if ( res == 1 ) {
// success
printf( "Congrats, you entered %d\n", i );
} else {
// failed, just ignore the buffer
printf( "Ignoring bad input\n" );
}
} else {
// EOF to start with
printf( "Found EOF\n" );
}
}
int main() {
// choose one
// use_scanf();
use_fgets();
return 0;
}