Where does `getchar()` store the user input?

后端 未结 7 2110
情深已故
情深已故 2020-12-16 04:25

I\'ve started reading \"The C Programming Language\" (K&R) and I have a doubt about the getchar() function.

For example this code:

#         


        
7条回答
  •  执笔经年
    2020-12-16 05:17

    Something here is buffered. e.g. the stdout FILE* which putchar writes to might be line.buffered. When the program ends(or encounters a newline) such a FILE* will be fflush()'ed and you'll see the output.

    In some cases the actual terminal you're viewing might buffer the output until a newline, or until the terminal itself is instructed to flush it's buffer, which might be the case when the current foreground program exits sincei it wants to present a new prompt.

    Now, what's likely to be the actual case here, is that's it's the input that is buffered(in addition to the output :-) ) When you press the keys it'll appear on your terminal window. However the terminal won't send those characters to your application, it will buffer it until you instruct it to be the end-of-input with Ctrl+D, and possibly a newline as well. Here's another version to play around and ponder about:

    int main() {
      int c;
       while((c = getchar()) != EOF) {
         if(c != '\n')
            putchar(c);
       }
        return 0;
    }
    

    Try feeding your program a sentence, and hit Enter. And do the same if you comment out if(c != '\n') Maybe you can determine if your input, output or both are buffered in some way. THis becomes more interesting if you run the above like: ./mytest | ./mytest

    (As sidecomment, note that CTRD+D isn't a character, nor is it EOF. But on some systems it'll result closing the input stream which again will raise EOF to anyone attempting to read from the stream.)

提交回复
热议问题