0

I was going through K&R's the C Programming Language, and came across this bit of code:

main()
{
  int c;

  while ((c=getchar()) != EOF)
    putchar(c);
}

I understand the reason the above code doesn't print one character at a time, immediately after getchar() gets the character input from the stdin, is because stdin only sends the input to the program's input buffer after the user hits Enter.

However, the function getchar() still reads one character at a time from the input buffer, and passes said character to putchar() to print. Why doesn't putchar() print the character immediately after getting it? Does it also wait for a newline character before printing, and store everything in its own buffer?

Somenath Sinha
  • 1,174
  • 3
  • 16
  • 35
  • Tl;Dr Your stdout stream is line buffered, so it will not print immideatly. Set it to unbuffered or flush it with fflush(stdout) to do so – Magisch Feb 09 '16 at 07:05
  • Take a look [HERE](http://man7.org/linux/man-pages/man3/setbuf.3.html) – LPs Feb 09 '16 at 07:06
  • How do you know putchar doesn't print the character immediately after getting it? – user253751 Feb 09 '16 at 07:08
  • @immibis Then the output for "abc" would look like "aabbcc", i.e., each character would have been printed immediately after getting it. – Somenath Sinha Feb 09 '16 at 07:12
  • @SomenathSinha But I thought you already established that `getchar` doesn't return any characters until you press enter. If `getchar` is still waiting for you to press enter then obviously your program hasn't called `putchar` yet. – user253751 Feb 09 '16 at 07:22
  • @immibis That makes total sense. Thank you for the explanation. – Somenath Sinha Feb 09 '16 at 07:26

0 Answers0