Nizde
Nizde

Reputation: 11

Why does getchar() return more than one character?

While trying different things with getchar I figured out that it usually only safes on character in an variable. Somehow when I use a while loop the behaviour changes and it returns more characters if the input is more than one.

Here is my example code for "normal" behaviour. putchar() return only one character even more are put in:

#include <stdio.h>

main() {
    char c;

    printf("Type a character in here: ");
    c = getchar();
    printf("You just typed : ");
    putchar(c);
    
}

Somehow when I want to use it in a while loop the putchar() function returns more than one character if more are put in:

Here is the second part:

#include <stdio.h>

void print_input();

main() {
    char c;

    printf("Type a character in here: ");
    c = getchar();
    printf("You just typed : ");
    putchar(c);

    print_input();  
}


void print_input() {
    char ch = 'x';
    while (ch != '#') {
        ch = getchar();
        putchar(ch);
    }
    return;
}

Additional question: While running this in debugger the behaviour somehow is different than if I try this in runtime. Why is that so?

Upvotes: 1

Views: 1117

Answers (1)

Suciu Eus
Suciu Eus

Reputation: 189

When you enter multiple chars and hit enter, the program will see that whole input (because it's line buffered). So multiple calls to getchar will return subsequent characters and remove them from the stream:

Try to play with this:

char c;
char d;

printf("Type chars in here: ");
c = getchar();
d = getchar();

printf("C: %c \n", c);
printf("D: %c", d);

This is duplicated with: How is the "getchar()" function able to take multiple characters as input?

You can read more there.

Upvotes: 1

Related Questions