scanf导致C中的无限循环

问题描述 投票:1回答:2

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

我正在编写大学课程程序,但我感到困惑,为什么不调用下面的scanf函数,从而导致无限循环。

我尝试过将scanf放在函数外部,两次调用,一次是从内部调用,一次是从外部调用,还有其他几种方法。我在网上阅读了这些错误提示可能会有所帮助,但并没有

有什么建议吗?

// 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);
}

编辑刚刚意识到我没有提及任何事情。当我输入实际数字时,该程序可以完美运行。我想确保用户输入的不是字符串,这不会导致程序无限循环。

c loops scanf infinite-loop
2个回答
3
投票

类似非数字输入位于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: ");
}

2
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.