Jimmy Chung
Jimmy Chung

Reputation: 31

Why is the getchar() at the end necessary in this function? I don't see why it's there

void getInputData(void) {
    char c = 0;
    while (c != 'x') {
        printf("Enter a letter:");
        fflush(stdout);
        c = getchar();
        printf("You entered: %c \n",c);
        fflush(stdout);
        getchar();
    }
    printf("\nYou entered x and the loop exited\n");
}

Why is the getchar() at the end necessary in this function? I don't see why it's there.

Upvotes: 1

Views: 525

Answers (1)

MrDonMatti
MrDonMatti

Reputation: 74

Suppose you are using line-buffering in your program, perfect user inputs every time following letters until hits 'x':
T\n
H\n
I\n
S\n
x\n
Sending data works only when you press ENTER/RETURN key from keyboard. You should process \n newline character in order to get next character, that is why using getchar() is necessary.

Upvotes: 1

Related Questions