scanf在C中导致无限循环 [英] scanf causing infinite loop in C

查看:66
本文介绍了scanf在C中导致无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am relatively new to C, but I have been programming for a few years now.

我正在为一个大学班编写一个程序,但我很困惑为什么不调用下面的scanf函数,从而导致无限循环.

I am writing a program for a college class, and I am confused why the scanf function below is not called, resulting in an infinite loop.

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

I have tried having my scanf outside the function, calling it twice, once from within, once from out, and a few other ways. I read online that the fflush might help, but it hasn't

有什么建议吗?

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

编辑仅实现了我忘记提及某些事情.当我输入一个实际数字时,该程序可以完美运行.我想确保用户输入的不是字符串,这不会导致程序无限循环.

EDIT JUST REALIZED I FORGOT TO MENTION SOMETHING. This program works perfectly when I enter an actual number. I want to make it safe for if the user enters something that isn't a string, it won't cause the program to loop infinitely.

推荐答案

非数字输入很可能在 stdin 中.OP的代码不会消耗该代码.结果:无限循环.

Likely non-numeric input is in stdin. OP's code does not consume that. Result: infinite loop.

更好地使用 fgets().

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

Yet if OP is determined to use scanf(), test its output and consume non-numeric input as needed.

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: ");
}

这篇关于scanf在C中导致无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆