You're almost certainly entering a non-numeric value, which will cause the first scanf
to fail, returning zero and (this is the important bit) leaving the stream pointer exactly where it was before the scanf
call.
That means the next time you call it, it will simply try to read the same data.
The return value of zero is a dead giveaway - scanf
returns the number of items successfully scanned, so zero means you didn't give it a number.
If you enter numbers, it works fine, as per the following code:
#include <stdio.h>
int main(int argc, char const *argv[])
{
int n;
int i = scanf("%d", &n);
printf(">> %d %d\n", i, n);
int j = scanf("%d", &n);
printf(">> %d %d\n", j, n);
return 0;
}
When you run that and enter 41
and 32
, you see:
41
>> 1 41
32
>> 1 32
Every C programmer at some point in their career comes up against the inadequacies of user input in that language. Your best bet for line based input is to simply find a function that does it well, then use sscanf
on the resultant string.
One that ensures lines are the basic unit, and can handle buffer overflows and making sure excess data doesn't "corrupt" future input.
Here's one I prepared earlier.