1

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;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
Pedro Luiz
  • 33
  • 3
  • 1
    What would your second program do if the user typed "123cheesesandwich" at the first prompt? – zwol Sep 29 '22 at 16:51
  • You can use `fgets` if you don't want a loop. Although it's a bit fragile; `getline` is probably safer. – rici Sep 29 '22 at 17:03
  • 1
    By the way, `main` returns an `int`, not a `short`. Your prototype is undefined behaviour unless your compilation environment explicitly allows that prototype. – rici Sep 29 '22 at 17:04
  • 1
    `getchar` returns an `int`. If you assign it to `char c`, then you may get false positives as `c == EOF` is true sometimes when `getchar` did not actually return EOF. Never assign the value returned by `getchar` to a variable of type `char`. – William Pursell Sep 29 '22 at 17:06
  • Thank you all for your advices!! I really appreciate that. – Pedro Luiz Sep 29 '22 at 17:22
  • 1
    Oh! I forgot one thing... How about scanf(" %c", &char_test)? – Pedro Luiz Sep 29 '22 at 17:39
  • 1
    [`scanf` is broken as specified and should not be used at all](https://stackoverflow.com/questions/58403537/what-can-i-use-for-input-conversion-instead-of-scanf). – zwol Sep 29 '22 at 18:01

1 Answers1

1

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) {
zwol
  • 135,547
  • 38
  • 252
  • 361
chqrlie
  • 131,814
  • 10
  • 121
  • 189
  • Thanks!! Also, why scanf(" %c", &char_test) is not correct? – Pedro Luiz Sep 29 '22 at 17:45
  • @PedroLuiz: for the same reason stated here above: if the user typed `43 ab` when prompted to `Insert a number: `, the program will read the number `43`, then output `Insert a character: ` and `scanf(" %c", &char_test)` will read the `a` pending in `stdin`. – chqrlie Sep 29 '22 at 18:29