When scanf does not succeed, it leaves the input in the stream. You need to ignore the rest of the line and ask the user to provide the input again. You can add a function like:
void ignoreRestOfLine(FILE* fp)
{
int c;
while ( (c = fgetc(fp)) != EOF && c != '\n');
}
and call it from main:
if(scanf("%d", &age) > 0) {
printf("You are %d years old!\n", age);
} else {
// Ignore rest of the line and continue with the loop.
ignoreRestOfLine(stdin);
}
Another option is to read the data a line at a time and use sscanf to extract the number from the line.
char line[100]; // Make it large enough
while (age != 0)
{
printf("How old are you? ");
if ( fgets(line, sizeof(line), stdin) == NULL )
{
// Problem reading a line of text.
// Deal with it.
break;
}
else
{
if(sscanf(line, "%d", &age) > 0)
{
printf("You are %d years old!\n", age);
}
}
// Try to read again
}
dremains in the input buffer, and will stay there no matter how many times you try to readint. I suggest reading withfgetsinto a string and then extracting theintwithsscanf.int. The scan stops at the first non-numeric character, which remains in the input buffer.scanfusually readsstdinthrough a buffer. I believe it is possible to disable the buffer, but it's a perverse way of handling the situation. The guys who designed the OS did it for a reason.