Search code examples
cgetchar

How to tell `getchar()` to go back to the beginning of the buffer?


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");
}

Solution

  • 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.