Reputation: 188
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?
Upvotes: 0
Views: 85
Reputation: 123578
Even if If write many characters in the input and press enter, it only prints the first character.
Because ... that's what you told it to do. getchar
returns a single character from the input stream (or EOF
if end-of-file was signaled); it doesn't bother to look for any following characters.
You wrote your program to read a single character from the input stream, print that character, and then exit. Any additional characters in the input stream are simply discarded when the program exits.
When I write multiple characters, it prints all of them.
Again, because that's what you told it to do. You told your program to read a character and while it's not EOF
, print it and then read the next character.
Upvotes: 0
Reputation: 4608
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 getchar
function 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 next getchar
call.
Example:
123456789
ENTER.123456789\n
getchar
will return '1'
getchar
will return '2'
...
'\n'
Your code:
'\n'
character too.Upvotes: 4