fgetc(stdin) in a loop is producing strange behaviour

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

    There are two characters: a and \n (newline). Your loop reads reads the a, then loops and prints "hello world !". It then sees \n and loops and prints "hello world !". When you type a+\n in the terminal, it's storing the two characters in the stdin buffer. fgetc(stdin); will read from the stdin buffer if there is a char available, otherwise it waits until a char is added to the buffer.

    Since terminals are line-buffered (ie, do not send the content to the program until a newline is reached) you have a few options:

    • read the entire line into a buffer, but take only the first character
    • ignore newlines
    • turn off line-buffering

    To turn off line buffering, look at http://c-faq.com/osdep/cbreak.html and http://www.flipcode.com/archives/_kbhit_for_Linux.shtml and http://ubuntuforums.org/showthread.php?t=225713 (although I have not tested any of the code here).

提交回复
热议问题