c - 非数字输入导致死循环

标签 c loops input do-while

由于某种原因,如果用户输入了错误的数据类型,例如“j”或“%”,循环将停止要求输入并继续显示“输入整数>”一遍又一遍。如何让程序处理错误的输入?为什么输入非数字值会导致如此奇怪的行为?

#define SENTINEL 0;
int main(void) {
  int sum = 0; /* The sum of numbers already read */
  int current; /* The number just read */

  do {
    printf("\nEnter an integer > ");
    scanf("%d", &current);
    if (current > SENTINEL)
      sum = sum + current;
  } while (current > SENTINEL);
  printf("\nThe sum is %d\n", sum);
}

最佳答案

如果 scanf() 未能找到匹配的输入,current 变量将保持不变:检查 scanf() 的返回值:

/* scanf() returns the number of assignments made.
   In this case, that should be 1. */
if (1 != scanf("%d", &current)) break;

如果您希望在无效输入后继续接受输入,则需要从 stdin 读取无效数据,因为它将保留下来,如 pmg 所指出的。在评论中。一种可能的方法是使用格式说明符 "%*s" 读取输入但不执行赋值:

if (1 != scanf("%d", &current))
{
    scanf("%*s");
}
else
{
}

关于c - 非数字输入导致死循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11314246/

相关文章:

Java:如何禁用 JSpinner 蜂鸣声

javascript - 使用可选的字母前缀将输入屏蔽为电话号码格式

c - 具有包含 char * 的结构类型的 out 参数的公共(public) API 设计

c++ - 循环和if的优化

C++ 循环 - 流错误?

jquery - 发现任何元素是否具有 jQuery 中的任何类

python - 使用 BeautifulSoup 进行 HTML 解析

c - 使用 scanf 的选择性输入。可能只读取 ascii 0x79 和 0x6e

c - 在双向链表中的给定节点之前插入一个节点

在 Eclipse 中创建一个独立的可执行文件