talopl
talopl

Reputation: 188

Why does getchar in C accept many characters in a loop but not outside one

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

Answers (2)

John Bode
John Bode

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

gulpr
gulpr

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:

  1. you enter 123456789ENTER.
  2. the buffer contains 123456789\n
  3. first call to getchar will return '1'
  4. second call to getchar will return '2'

...

  1. tenth call will return '\n'

Your code:

  • Your first program reads one character from this buffer, prints it and then terminates.
  • your second program is looping taking the characters from this buffer one by one including the new line '\n' character too.

Upvotes: 4

Related Questions