`getchar()` gives the same output as the input string

Shubham picture Shubham · Sep 9, 2010 · Viewed 104k times · Source

I am confused by a program mentioned in K&R that uses getchar(). It gives the same output as the input string:

#include <stdio.h>

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

Why does it print the whole string? I would expect it to read a character and ask again for the input.

And, are all strings we enter terminated by an EOF?

Answer

Erich Kitzmueller picture Erich Kitzmueller · Sep 9, 2010

In the simple setup you are likely using, getchar works with buffered input, so you have to press enter before getchar gets anything to read. Strings are not terminated by EOF; in fact, EOF is not really a character, but a magic value that indicates the end of the file. But EOF is not part of the string read. It's what getchar returns when there is nothing left to read.