An example
Code:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int main ( ) {
char buff[BUFSIZ];
if ( fgets(buff, BUFSIZ, stdin ) ) {
char *endp;
errno = 0;
long temp = strtol(buff,&endp,0);
if ( buff == endp ) {
printf("Not an integer\n");
}
else if ( errno != 0 ) {
printf("Way out of range\n");
} else {
// it's a valid integer, is it what we want?
if ( temp >= 1 && temp <= 2 ) {
printf("Congrats!\n");
// It's all good, do our thing
} else {
printf("Out of range\n");
}
}
} else {
printf("EOF, or stdin broke\n");
}
}
$ gcc foo.c
$ ./a.out
dfgf
Not an integer
$ ./a.out
EOF, or stdin broke
$ ./a.out
1323435465768797946353
Way out of range
$ ./a.out
3443
Out of range
$ ./a.out
2
Congrats!
So yeah, you can make it bomb proof, but it takes a lot more code than just calling scanf.