I am a complete beginner in C, so sorry if this question sounds too trivial.
My understanding of getchar()
and putchar()
is that they process text streams one character at a time. Let's say I have this program that takes textual input from the user and displays it on the screen:
#include <stdio.h>
main(){
int c;
c = getchar();
while(c!= EOF){
putchar(c);
c=getchar();
}
}
Here's what I think is happening:
Suppose I run this program and I enter the word Hi. getchar
reads the first character (namely H
) and stores it in c
. Then the program enters the while loop and puts H
to the screen. Then it gets the next character (i
) and prints it. Then comes the EOF
and when getchar
assigns the value to c, the while loop ends. So, according to this interpretation of what has happened, the program should end after printing all the characters and having reached the end of file.
When I run the program, however, after printing the string, the program waits to receive additional input, meaning it doesn't end, rather waits for the user to input more text streams.
Why does this happen and where do I get it wrong?