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;
}
3
  • stackoverflow.com/questions/7898215/… Commented Feb 15, 2017 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. Commented Feb 15, 2017 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. Commented Feb 15, 2017 at 18:32

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.