Thread: Beginner's question on getchar, putchar, and buffer

  1. #1
    Registered User
    Join Date
    Nov 2016
    Posts
    1

    Beginner's question on getchar, putchar, and buffer

    I just started studying C and have no idea how computer works. So it could be dumb question.


    When I saw this code,


    Code:
        #include <stdio.h>
        main()
        {
            int c;
        
            while ((c = getchar()) != EOF)
                putchar(c);
        }
    The way it works I assume is that when I type a character, it would print same character instantly before I type next character. For instance, if I type "apple", I thought it would run like this.


    a a p p p p l l e e


    but rather it just printed same character string I typed til enter. So I googled, and found something called "buffer". What I figured out myself is that when I type something, it is not read by program until I press enter, and when I press enter, the character string in buffer is read by program. Then program prints. Is this how buffer and program works?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Yes, standard input is by default line buffered.
    The runtime environment collects input until a newline (or end of file) is seen, at which point each call to getchar() in your loop will return immediately until the buffer is once again empty.

    You can alter the buffering mode by using this right at the start of your program.
    setvbuf - C++ Reference
    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. Getchar,putchar
    By Filster in forum C Programming
    Replies: 26
    Last Post: 08-03-2011, 04:45 PM
  2. getchar() and putchar()
    By kawaikx15 in forum C Programming
    Replies: 5
    Last Post: 04-13-2011, 11:02 AM
  3. getchar and putchar
    By BEN10 in forum C Programming
    Replies: 4
    Last Post: 03-11-2009, 10:29 PM
  4. need help please! getchar, putchar, etc.
    By sue in forum C Programming
    Replies: 1
    Last Post: 03-21-2003, 08:40 PM

Tags for this Thread