Koli96 Koli96 - 1 year ago 126
C Question

Scanf returns 0 without waiting for input

I have never programmed in C and today I have to write small code. Program is very easy - I want to add two integers.
But when I'm trying to check if given input is a number and first scanf returns 0, the second one returns 0 too without waiting for input.

int main()
int a = 0;
int b = 0;
printf("Number a:\n");
if (scanf("%d", &a) != 1)
printf("Not a number. a=0!\n");
a = 0;
printf("Number b:\n");
if (scanf("%d", &b) != 1)
printf("Not a number. b=0!\n");
b = 0;
printf("%d\n", a+b);
return 0;

Answer Source

That is because, once the first scanf() failed, it is probably because of matching failure, and the input which caused the matching failure, remains inside the input buffer, waiting to be consumed by next call.

Thus, the next call to scanf() also try to consume the same invalid input residing in the input buffer immediately, without waiting for the explicit external user input as the input buffer is not empty.

Solution: After the first input fails for scanf(), you have to clean up the input buffer, for a trivial example, something like while (getchar() != '\n'); should do the job.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download