Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
650 views
in Technique[技术] by (71.8m points)

c - What is the standard input buffer?

#include <stdio.h>

int main(void)
{
    int c;
    c = getchar();
    putchar(c);
    c = getchar();
    putchar(c);
    c = getchar();
    putchar(c);
    return 0;
}

I want to understand why the function that is called three times working with a line that was entered only once. Some guy explained, that we working with the standard input buffer in this situation, and that is a piece of memory. I want to read something about it. Can you advise me some resources?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is a feature of your terminal (the command line window).

By default, the terminal will collect input from the user until he presses Enter/Return. Then the whole line is pushed to the input filestream of your program (stdin, that is; since you use <stdio.h> rather than <iostream>, there's no cin involved).

This is useful because your program does not have to deal with interpreting all keyboard events (e.g. remove letters when Backspace is pressed). Programs which want to handle the keyboard themselves can disable this default input mode. I think the relevant Google keywords for that are terminfo or termcap.

Specifically concerning your question, one line of input is good for three getchar() calls if it contains three characters. If you entered only one character, your program should wait on the subsequent getchar() calls for more input.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...