In the following program:
#include <stdio.h>
int main() {
int c;
c = getchar();
putchar(c);
}
Even if If write many characters in the input and press enter, it only prints the first character.
However in the following program:
#include <stdio.h>
int main() {
int c;
c = getchar();
while (c != EOF) {
putchar(c);
c = getchar();
}
}
When I write multiple characters, it prints all of them.
My question is the following: Why, when I press enter, doesn't it print only the first character in my input as in the first program and how come the condition in while is evaluated before putchar(c) is called?
The input is line-buffered. When you enter characters and hit ENTER the buffer contains all the characters you have entered +
'\n'(new line).The
getcharfunction takes one character from this buffer and returns it. It does not discard the rest of this buffer. Other characters entered will be available for the nextgetcharcall.Example:
123456789ENTER.123456789\ngetcharwill return'1'getcharwill return'2'...'\n'Your code:
'\n'character too.