I was experimenting with C's fgetc()
and ran into a strange problem.
I typed the following code below:
int answer = 0;
printf("Input1\n");
answer = fgetc(stdin);
printf("%c\n", answer);
printf("Input2\n");
answer = fgetc(stdin);
printf("%c\n", answer);
However, every time I enter a value other than a space, this happens:
Input1
1
1
Input2 # It doesn't wait for my input here
Could anyone tell me what I'm doing wrong? I've tried flushing stdin
and I've also tried using rewind
on stdin
. However, none of these work.
If you type in 1
followed by enter, there is \n
char at the end of input. The second fgetc
will read the \n
character.
For debugging (as suggested in comments) you can replace printf("%c\n", answer)
with
printf("Got %d (%c)\n", answer, (isprint(answer) ? answer : '.'));
The result should be:
Input1
1
Got 49 (1)
Input2
Got 10 (.) <- new line