Perhaps this will explain.
Code:
#include <stdio.h>
int myGetChar(void) {
int ch = getchar();
printf("\nGetchar called: returning ch=%c (decimal=%d)\n", ch,ch);
return ch;
}
int myPutChar(int ch) {
printf("Putchar called: ch=%c\n", ch);
putchar(ch);
return ch;
}
int main() {
int c;
while ((c = myGetChar()) != EOF) {
myPutChar(c);
}
return 0;
}
$ gcc bar.c
$ ./a.out
hello
Getchar called: returning ch=h (decimal=104)
Putchar called: ch=h
h
Getchar called: returning ch=e (decimal=101)
Putchar called: ch=e
e
Getchar called: returning ch=l (decimal=108)
Putchar called: ch=l
l
Getchar called: returning ch=l (decimal=108)
Putchar called: ch=l
l
Getchar called: returning ch=o (decimal=111)
Putchar called: ch=o
o
Getchar called: returning ch=
(decimal=10)
Putchar called: ch=
Getchar called: returning ch=� (decimal=-1)
Things to note:
1. stdin is line buffered, so the code doesn't run until return is pressed.
2. when a newline is entered, the loop runs until there is no more input (ie, the newline just entered)
3. if EOF is signalled (by pressing ctrl-d (linux/unix) or ctrl-z (dos)), getchar returns the constant EOF (which happens to be -1 on my machine).
Since the condition is != EOF, the putchar does NOT get called in this case.