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?
In the simple setup you are likely using,
getcharworks with buffered input, so you have to press enter before getchar gets anything to read. Strings are not terminated byEOF; in fact,EOFis not really a character, but a magic value that indicates the end of the file. ButEOFis not part of the string read. It’s whatgetcharreturns when there is nothing left to read.