fgetc(stdin) in a loop is producing strange behaviour

后端 未结 4 495
别跟我提以往
别跟我提以往 2020-12-11 08:24

I have this code

while(1){
    printf(\"hello world !\\n\");
    fgetc(stdin);
}

when this runs and I enter a letter like this:

<         


        
4条回答
  •  攒了一身酷
    2020-12-11 09:03

    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.

提交回复
热议问题