0

If I enter a number, everything runs fine. But when I enter a letter it keeps spamming "enter a number". It does not ask for input again. How can I fix this problem?

#include <stdio.h>

int main() {

    int number = 0;

    int status = 0;
    do{
        printf("enter a number\n");
        status = scanf("%d", &number);
    } while (status != 1);

    printf("you chose number %d", number);

    return 0;
}
user2997204
  • 1,344
  • 2
  • 12
  • 24
  • https://stackoverflow.com/questions/7898215/how-to-clear-input-buffer-in-c – AntonH Feb 15 '17 at 18:28
  • 1
    @AntonH I don't think that is a duplicate: almost the *opposite* problem. Here the input is blocked by a letter that will not go away until you find way of clearing the input. One easy way to get round it is to read the input with `fgets` and apply `sscanf` to that string. If the scan fails, you just input another string. – Weather Vane Feb 15 '17 at 18:32
  • 2
    Many duplicates of this question exist. When you enter letters and `scanf()` expects a number, the letters are left in the input stream. You must clear the input stream. Do not use `fflush(stdin)`, as some will recommend; the Standard explicitly says that this leads to undefined behavior, though some implementations, notably MS, define this behavior. – ad absurdum Feb 15 '17 at 18:32

0 Answers0