Thread: Why getchar()'s behavior so strange in this case?

  1. #1
    Registered User
    Join Date
    Sep 2018
    Posts
    21

    Why getchar()'s behavior so strange in this case?

    Hello all!
    I'm reading K&R about C language now. Could any one explain so strange behavior?
    Code:
    while ((c = getchar()) != EOF) { printf("%c", c); }
    The printf function prints all entered characters in Terminal only when the Enter key was pressed. Why?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,596
    Because the input stream is line-buffered by default.

    That is, the C runtime library will try to read a complete line into an internal buffer, before returning to your program.
    Where your repeated calls to getchar() will fetch characters out of that internal buffer up to the newline (and the whole thing repeats).
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 01-02-2017, 08:15 PM
  2. Behavior of getchar() and putchar()
    By Strict in forum C Programming
    Replies: 5
    Last Post: 07-06-2016, 02:22 PM
  3. Need help, please - very strange behavior
    By snork in forum C Programming
    Replies: 16
    Last Post: 09-26-2011, 01:36 AM
  4. Newbie question about getchar() behavior.
    By Packeteer in forum C Programming
    Replies: 21
    Last Post: 06-18-2010, 05:52 PM
  5. strange std::map behavior
    By manav in forum C++ Programming
    Replies: 63
    Last Post: 04-11-2008, 08:00 AM

Tags for this Thread