scanf causing infinite loop in C

柔情痞子 提交于 2021-02-05 08:52:49

问题


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

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.

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

Any suggestions?

// 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.


回答1:


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

Better to use fgets().

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



回答2:


Use fgets to retrieve the input as a string and sscanf to convert it to a number. What this does is prevent errors in conversion from preventing reading from stdin. You could print the values of scanf return code and players to see what you are really receiving. You should also check for end of file which would also cause an infinite loop since there will not be any more input from EOF.



来源:https://stackoverflow.com/questions/32849647/scanf-causing-infinite-loop-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!