I\'m working on a challenge problem from my textbook where I\'m supposed to generate a random number between 1-10, let the user guess, and validate their response with isdigit()
You can use the return value of scanf
to determine whether the read was successful. So, there are two paths in your program, successful reading and failed reading:
int guess;
if (scanf("%d", &guess) == 1)
{
/* guess is read */
}
else
{
/* guess is not read */
}
In the first case, you do whatever your program logic says. In the else
case, you have to figure out "what was the problem", and "what to do about it":
int guess;
if (scanf("%d", &guess) == 1)
{
/* guess is read */
}
else
{
if (feof(stdin) || ferror(stdin))
{
fprintf(stderr, "Unexpected end of input or I/O error\n");
return EXIT_FAILURE;
}
/* if not file error, then the input wasn't a number */
/* let's skip the current line. */
while (!feof(stdin) && fgetc(stdin) != '\n');
}