Search code examples
cloopsscanfinfinite-loop

scanf causing infinite loop in C


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.


Solution

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