How c=getchar is using buffer to out textstream when I input text stream?

206 views Asked by At

I understand how this program shows how getchar is using buffer to copy and paste more than one character

#include <stdio.h>
main()
{
    int c;
    c=getchar();
    putchar(c);
    c=getchar();
    putchar(c);
}

but how does this code below

#include <stdio.h>
main()
{
    int c;

    c=getchar();
    while (c!= EOF)         // how does this program copy 12 and output 12. is a            
    {                           buffer being used? How so? 
       putchar(c);
        c=getchar();
    }
}

show a buffer being used... i dont get it and i dont see how its able to print 12 when i input 12. im new to C

2

There are 2 answers

16
Spikatrix On BEST ANSWER

getchar reads character by character from the standard input stream(stdin). The thing is, the terminal doesn't flush the typed data into the stdin until you press Enter. When you press it, characters are sent to the stdin with getchar reading each character and putchar outputting each one of them until EOF.

is a buffer being used?

No.... But sort-of.

0
Medinoc On

Yes, there is a buffer, hidden in the input stream. A "line" buffer to be precise: Characters are memorized in the stream until a newline is entered, and then sent to the process (at which point whatever blocking read function you're using -- be it getchar(), fgets(), or even read() -- returns).

In a loop calling getchar(), the function will keep returning characters from the stream until the newline character is returned, at which point the function will block again until there's another newline in the stream.