Do getchar() and putchar() read only one character each time they're called or do they read a stream of characters?

464 views Asked by At

There is something vague about the functionality of getchar(), putchar() in while loop for me.
In the following program that copies its input to its output:

#include <stdio.h>

main()
{
    int c;
    c = getchar();
    while (c != EOF) {
        putchar(c);
        c = getchar();
    }
}

1- how does getchar() store its value in c? If getchar() reads the next input character each time it's called, then if we input "Hello world", only "H" should be stored in c since getchar() was called only once before the while loop.
however If getchar() reads a stream of characters, then how is the value stored in a variable such as c which is not an array?

2- kind of the same question about putchar(). how does putchar() output a stream of characters if it only prints the next character each time it is called? in the while loop it should print only one character and then go to the next line and wait for the next character input. The while loop doesn't just execute the putchar(c) statement repeatedly to print the whole string. it loops over the whole block, right?

I think my consideration is that the program should read one character from input, go inside the while loop, print out the character if it's not EOF and wait for the next input. I don't understand how it prints a stream of characters...

1

There are 1 answers

1
user253751 On

getchar reads one character and putchar writes one character.

A while loop keeps running the whole block until the "condition" part (c != EOF) isn't true, then it moves on to the next statement after the block, like usual.

This is a very basic property of loops (all of them, not just while). If you got past loops in your textbook or tutorial you might want to go back and study them some more.

Your program reads one character, writes it, reads one, writes it, reads one, writes it, ..... until it reads EOF instead of a character.