Reputation: 63
#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?
Upvotes: 6
Views: 6078
Reputation: 1
getchar() actually reads your input from the input buffer.
what do I mean by that is this?
say we have this statement :
a = getchar()
On the terminal you entered :
G
However you didnt only enter G you actually entered G and then pressed
enter, enter basically is the new line character. So what you entered is
\
G\n.
So your buffer now looks like
G \n
Now, its a wrong concept that getchar() reads one character only from the keyboard. It rather reads the first character in the input buffer. So when
b = getchar() gets executed, the \n character gets stored in it.
NOTE: Characters get removed from the buffer when it is used.
NOTE: There are manual ways to flush the buffer.
Upvotes: 0
Reputation: 5555
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.
Upvotes: 4