Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fgetc(stdin) in a loop is producing strange behaviour

Tags:

c

fgetc

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 ?

like image 692
lilroo Avatar asked Dec 04 '22 14:12

lilroo


1 Answers

That's because you actually enter two characters: 'a' and a newline. Also, since terminal is normally line-buffered your program will only see your input once you hit the newline. It'll be informative to enter a longer line of text, too.

If you want to change this behavior you have two options: reading entire lines (i.e. all characters up to a newline or end-of-file) or switching terminal to non-canonical mode. The latter makes sense if you're working on an interactive terminal application like a text editor. See termios manpage for details. In short, you'll want to set MIN and TIME options to zero to make reads from terminal return immediately as data becomes available. If you do go down this path, make sure you switch the terminal back when you exit, including due to reception of a signal.

fflush() affects the output, not the input.

like image 129
Adam Zalcman Avatar answered Dec 29 '22 00:12

Adam Zalcman