According to the definition of getchar()
, it reads a character from the standard input. Unfortunately stdin
is mistaken for keyboard which might not be the case for getchar
. getchar
uses a buffer as stdin
and reads a single character at a time. In your case since there is no EOF
, the getchar
and putchar
are running multiple times and it looks to you as it the whole string is being printed out at a time. Make a small change and you will understand:
putchar(c);
printf("\n");
c = getchar();
Now look at the output compared to the original code.
Another example that will explain you the concept of getchar
and buffered stdin
:
void main(){
int c;
printf("Enter character");
c = getchar();
putchar();
c = getchar();
putchar();
}
Enter two characters in the first case. The second time when getchar
is running are you entering any character? NO but still putchar
works.
This ultimately means there is a buffer and when ever you are typing something and click enter this goes and settles in the buffer. getchar
uses this buffer as stdin
.