cbuffergetchar

Clearing keyboard buff in C with getchar()


I have this noob question:

#include <stdio.h>

unsigned short int main() {
    short int num_test = 0;
    char car_test;
    
    printf("Insert a number: ");
    scanf("%hd", &num_test);
    
    printf("Insert a character: ");
    scanf("%c", &car_test);

    return 0;
}

In the code above, car_teste would receive the value '\n', right? To prevent this, we should clean the keyboard buffer, right? Well, instead of doing this:

char c;
while ((c = getchar()) != '\n' && c != EOF) {}

Why we "can't" use this solution, for example?

#include <stdio.h>

unsigned short int main() {
    short int num_test = 0;
    char car_test, kb_buff;
    
    printf("Insert a number: ");
    scanf("%hd", &num_test);

    kb_buff = getchar();
    
    printf("Insert a character: ");
    scanf("%c", &car_test);

    return 0;
}

Solution

  • Your approach to flushing the rest of the input line is correct except for the type of c which must be int:

    int c;
    while ((c = getchar()) != EOF && c != '\n')
        continue;
    

    The alternative kb_buff = getchar(); may work but the user might have entered more characters after the number before hitting the Enter key, which the while loop will consume correctly.

    Note also that the prototype for your main function must be:

    int main(void) {