fgetc(stdin) in a loop is producing strange behaviour

后端 未结 4 507
别跟我提以往
别跟我提以往 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:21

    Terminals tend to be line-buffered, meaning that stream contents are accessible on a line-by-line basis.

    So, when fgetc starts 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.

提交回复
热议问题