Uclydde
Uclydde

Reputation: 1414

Loop is not working correctly

I'm trying to make my loop take a user input, and if the value is 1 through 9, the loop finishes (this part is working properly). But if the user input is not a number 1 - 9, then the program should display an error message, then ask for user input once more, and re-check if the input is a number 1 - 9. When testing this, if I input the letter 'g', then the program spits out the error message indefinitely, rather than just once. Why is this?

Here's the code:

int playerMove;

printf("Please enter a number 1 - 9:\n");

  for(;;)
  {
   scanf("%d", &playerMove);

    if(playerMove > 0 && playerMove < 10)
    {
      printf("\nYou have selected position %d. \n\n", playerMove);
      break;
    }

    else 
    {
      printf("Invalid selection. Please enter a number 1 - 9:\n");
    }
  }

Upvotes: 0

Views: 121

Answers (2)

dbush
dbush

Reputation: 223699

When scanf encounters characters that don't match the given format specifier, those characters are left in the input buffer. The %d format specifier expects decimal digits, so it stops reading once a non-digit is read.

By entering "g", the scanf call reads nothing and the "g" is left in the buffer. The same happens on subsequent iterations, resulting in an infinite loop.

Use fgets instead to read a line of text, then use sscanf to attempt to read a number from that line. If it returns 1 the conversion was successful. If it returns 0, non-numeric input was read and you read another line:

for(;;) {
    char line[100];
    fgets(line, sizeof(line), stdin);
    int result = sscanf(line, "%d", &playerMove);

    if (result == 1 && playerMove > 0 && playerMove < 10)
        printf("\nYou have selected position %d. \n\n", playerMove);
        break;
    } else {
        printf("Invalid selection. Please enter a number 1 - 9:\n");
    }
}

Upvotes: 3

jaudo
jaudo

Reputation: 2122

If you do not trust user input, you should read input as a string (with gets for example) and then parse this string.

Upvotes: 0

Related Questions