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; }
fgetsand applysscanfto that string. If the scan fails, you just input another string.scanf()expects a number, the letters are left in the input stream. You must clear the input stream. Do not usefflush(stdin), as some will recommend; the Standard explicitly says that this leads to undefined behavior, though some implementations, notably MS, define this behavior.