http://faq.cprogramming.com/cgi-bin/...&id=1043284351
Where you might do
Code:
scanf( "%d", &myInt );
I would do
Code:
char buff[BUFSIZ];
fgets( buff, sizeof buff, stdin );
sscanf ( buff, "%d", &myInt );
You might think that's hard work, but wait until you've added error checking
Code:
int r, c;
if ( (r=scanf( "%d", &myInt )) == 1 ) {
// success
// now get rid of the trailing chars up to the newline
while ( (c=getchar()) != '\n' && c != EOF ) { }
} else
if ( r == 0 ) {
// it wasn't an integer, an error message
printf( "That wasn't an integer\n" );
// now get rid of the trailing chars up to the newline
while ( (c=getchar()) != '\n' && c != EOF ) { }
} else {
// r == EOF
// Now what? the user has lost all interest in the program - tidy up and bail out
}
Compare with
Code:
char buff[BUFSIZ];
if ( fgets( buff, sizeof buff, stdin ) != NULL ) {
if ( sscanf ( buff, "%d", &myInt ) == 1 ) {
// success
} else {
// it wasn't an integer, an error message
printf( "That wasn't an integer\n" );
}
} else {
// Now what? the user has lost all interest in the program - tidy up and bail out
}
Oh, and as zacs7 mentions, strtol() is better than sscanf(), since it detects numeric overflows.