I've started reading "The C Programming Language" (K&R) and I have a doubt about the getchar()
function.
For example this code:
#include <stdio.h>
main()
{
int c;
c = getchar();
putchar(c);
printf("\n");
}
Typing toomanychars
+ CTRL+D (EOF) prints just t
. I think that's expected since it's the first character introduced.
But then this other piece of code:
#include <stdio.h>
main()
{
int c;
while((c = getchar()) != EOF)
putchar(c);
}
Typing toomanychars
+ CTRL+D (EOF) prints toomanychars
.
My question is, why does this happens if I only have a single char variable? where are the rest of the characters stored?
EDIT:
Thanks to everyone for the answers, I start to get it now... only one catch:
The first program exits when given CTRL+D while the second prints the whole string and then waits for more user input. Why does it waits for another string and does not exit like the first?
getchar
gets a single character from the standard input, which in this case is the keyboard buffer.
In the second example, the getchar
function is in a while
loop which continues until it encounters a EOF
, so it will keep looping and retrieve a character (and print the character to screen) until the input becomes empty.
Successive calls to getchar
will get successive characters which are coming from the input.
Oh, and don't feel bad for asking this question -- I was puzzled when I first encountered this issue as well.