scanf() protection help
I've been trying to implement a protective measure for my scanf() functions in my program.
The goal is to get the input from the user, and then ask again if scanf doesn't successfully receive input. The problem here is is that when a user give the program bad input, (Like, a character for instance) the while loop just prints the "enter the integer" message on to infinity and doesn't re-evaluate the input.
printf("Enter an integer to be added to\n");
while (scanf("%d", &a) != 1);
printf("Enter a second integer to be added to the first\n");
while (scanf("%d", &b) != 1);
c = (a + b);
printf("%d + %d = %d\n", a,b,c);
Yes, you need to clear up whatever is in the input buffer (e.g. a letter). There is a FAQ entry for "How do I clear the input buffer" or something close to that title. FAQ's can be found at the top left of the page.
You still have a '\n' or some other char in the buffer. You probably want to clear the buffer by reading until you hit a '\n' char before you read from scanf().