Reputation: 984
The code below works like expected if the user enters only integers.
#include <stdio.h>
int main()
{
int input1, input2;
int error;
error = scanf("%d", &input1);
if( !error)
printf("Error: Your input was wrong\n");
else
printf("Your input was: %d\n", input1);
error = scanf("%d", &input2);
if( !error)
printf("Error: Your input was wrong");
else
printf("Your input was: %d\n", input2);
}
However if the user types in abcd
at the first prompt, the program prints out:
Error: Your input was wrong
Error: Your input was wrong
skipping the second scanf()
How can I "revive" stdin
once an input has failed, so that it can be reused?
Upvotes: 0
Views: 60
Reputation: 40145
if(!error){
printf("Error: Your input was wrong\n");
scanf("%*[^\n]");
} else
printf("Your input was: %d\n", input1);
Upvotes: 3