Reputation: 200
I am learning C from "The C Programming Language" and I have ran into something with getchar()
that confuses me. Apparently, when I call getchar()
in a program, the input text is stored in a buffer and then getchar()
reads the characters in this buffer one by one until it sees EOF
. Is it possible for me to instruct getchar()
to perform this process a second time on the same buffer? For instance, the second loop in the following program will not run for me. Is it possible to "reset" getchar()
after the first loop?
#include <stdio.h>
int main()
{ int c,d;
c = d = 0;
while((c = getchar()) != EOF) printf("foo");
while((d = getchar()) != EOF) printf("bar");
}
Upvotes: 1
Views: 3888
Reputation: 4877
To make it simple getchar() doesn't read in a buffer, but in the keyboard input stream, normally called stdin (standard input).
getchar() doesn't peek a char from the stream, but consumes a char for each call that means read & remove the char from the stream. So when you're at end of stream you'll get an eof (end of file) that informs you that there are no more chars in it.
Then the stdin is normally line buffered meaning that a full input line, a series of chars terminated by a newline, is made available at time.
Upvotes: 2
Reputation: 63124
It's not getchar()
that is buffered, but your terminal. Once you hit Enter, the terminal sends the whole line you typed at once to your program. From your program's point of view, there's no buffer, you just sat still for ten seconds, then typed a whole sentence in a blink.
You can verify that by crafting a loop that getchar()
's, and outputs the character it received immediately : the output will not be interleaved with the input, it will only appear once you've pressed Enter.
Thus, if you want to reuse what you know is a buffer, you need your program to read it into an actual buffer on its side via fgets()
, and then use that buffer as desired.
Upvotes: 3