I have this code
while(1){
printf("hello world !\n");
fgetc(stdin);
}
when this runs and I enter a letter like this:
hello world !
a
it ignores the fgetc(stdin) in the next loop and prints hello world twice without waiting for input.
hello world !
a
hello world !
hello world !
a
hello world !
hello world !
a
hello world !
hello world !
a
hello world !
hello world !
I have tried putting fflush(stdin) before or after the fgetc(stdin) but it still produces the same behaviour, what am I doing wrong ?
Terminals tend to be line-buffered, meaning that stream contents are accessible on a line-by-line basis.
So, when
fgetcstarts reading from STDIN, it’s reading a full line, which includes the newline character that ended that line. That’s the second character you’re reading.As for
fflush, that’s for flushing output buffers, not input buffers.So, what you want to do here is to purge the input buffer by reading from it until its empty, or just explicitly ignore newline characters.