【问题标题】:scanf causing infinite loop in Cscanf 在 C 中导致无限循环
【发布时间】:2015-12-27 06:26:48
【问题描述】:

我对 C 语言比较陌生,但我已经编程几年了。

我正在写一个大学班的程序,我很困惑为什么下面的scanf函数没有被调用,导致死循环。

我尝试让我的 scanf 在函数之外调用它两次,一次从内部调用,一次从外部调用,以及其他几种方式。我在网上读到 fflush 可能会有所帮助,但它没有

有什么建议吗?

// store starting variables
int players;

// print title

printf("*------------------------------------*\n");
printf("|                                    |\n");
printf("|                Wheel               |\n");
printf("|                 of                 |\n");
printf("|               Fortune              |\n");
printf("|                                    |\n");
printf("*------------------------------------*\n");
printf("\n\nHow many players are there?: ");

while(scanf("%d", &players) != 1 && players >= 0) {
    printf("That isn't a valid number of players. Try again: ");
    fflush(stdin);
}

编辑刚刚意识到我忘了提一些东西。当我输入一个实际数字时,这个程序可以完美运行。我想让它安全,如果用户输入的不是字符串,它不会导致程序无限循环。

【问题讨论】:

  • 不要fflush(stdin)
  • 逻辑看起来不对...你的意思是while(scanf("%d", &players) != 1 || players <= 0) {(如果scanf() 失败或没有玩家则循环)?另外,fflush(stdin) 不会清除所有平台上的输入流,所以在依赖它之前确保它在你的平台上工作。

标签: c loops scanf infinite-loop


【解决方案1】:

stdin 中可能是非数字输入。 OP 的代码不会消耗它。结果:无限循环。

最好使用fgets()

然而,如果 OP 确定使用 scanf(),请测试其输出并根据需要使用非数字输入。

int players;
int count;  // Count of fields scanned
while((count = scanf("%d", &players)) != 1 || players <= 0) {
  if (count == EOF) {
    Handle_end_of_file_or_input_error();
    return;

  // non-numeric input
  } else if (count == 0) {
    int ch;
    while (((ch = fgetc(stdin)) != '\n') && (ch != EOF)) {
      ; // get and toss data until end-of-line
    }

  // input out of range
  } else {
    ; // Maybe add detailed range prompt
  }  
  printf("That isn't a valid number of players. Try again: ");
}

【讨论】:

  • 我不相信你使用 fgets 而不是 scanf 有 100% 的把握。 scanf 的唯一问题是使用几乎总是错误的。
【解决方案2】:

使用 fgets 将输入检索为字符串,并使用 sscanf 将其转换为数字。这样做是为了防止转换错误阻止从标准输入读取。您可以打印 scanf 返回码和播放器的值,以查看您真正收到的内容。您还应该检查文件结尾,这也会导致无限循环,因为 EOF 将不再有任何输入。

【讨论】:

  • scanf 一直试图做的太多,迷惑了太多的初学者。 fgets 和 sscanf 一直有更好的机制分离。
  • 我确实做到了。我的 scanf 每次都返回 0。
  • scanf 的输入是什么? 0 表示它与格式化字符串不匹配。
猜你喜欢
  • 2016-06-05
  • 2013-12-20
  • 2012-10-05
  • 2023-03-24
  • 2012-09-27
相关资源
最近更新 更多