在 while 循环中使用 scanf() 检查输入类型

Checking input types with scanf() in a while loop

我一直在编写一个程序,它接受输入并检查数字是偶数还是奇数,如果输入是字符而不是数字,则输出错误消息我的初始代码是:

int main()
{
    int x;
    int check = scanf("%d", &x);
    printf("input: ");
    while(check != 1){ //means that the input is inappropriate 
       printf("Error!: unexpected input\n"); 
       printf("input: ");
       check = scanf("%d", &x);
    }
    if(x%2 == 0){
    printf("It's even\n");
    }else{
    printf("It's odd\n");
    }
return 0;
}

当我 运行 无限循环打印时 "Error!: unexpected input\n" 但是当我将以下语句放入 while 循环时,它可以正常工作,语句是:scanf("%s",&x); 有人可以解释这种行为吗?

int check = scanf("%d", &x); 不消耗 "input is a character not a number",将那个输入留在 stdin 中用于下一个输入函数。由于下一个输入函数是 check = scanf("%d", &x);,它不会消耗有问题的数据,因此循环会重复。

代码需要用 scanf("%d", ...)

以外的东西读取 "input is a character not a number"

建议不要使用 scanf(),而不是搞乱一个小修复。使用 fgets()getline() 读取输入,然后使用 ssscanf()strtol() 等解析

int main(void)     {
    int x;
    char buf[100];
    while (printf("input: "), fgets(buf, sizeof buf, stdin) != NULL) {
      int check = sscanf(buf, "%d", &x);
      if (check == 1) break;
      printf("Error!: unexpected input\n"); 
    }
    if(x%2 == 0){
      printf("It's even\n");
    }else{
      printf("It's odd\n");
    }
  return 0;
}