Non-numerical input causes endless loop

2019-05-26 19:03发布

For some reason, if the user inputs the wrong data type, such as 'j' or '%', the loop will stop asking for input and will keep displaying "Enter an integer >" over and over. How can I make the program handle bad inputs? And why does entering a non-numerical value cause such strange behavior?

#define SENTINEL 0;
int main(void) {
  int sum = 0; /* The sum of numbers already read */
  int current; /* The number just read */

  do {
    printf("\nEnter an integer > ");
    scanf("%d", &current);
    if (current > SENTINEL)
      sum = sum + current;
  } while (current > SENTINEL);
  printf("\nThe sum is %d\n", sum);
}

2条回答
The star\"
2楼-- · 2019-05-26 19:35

One way would be to read the input into a string and then convert the string to the data type you want.

My C is a bit rusty, but I recall using fgets() to read the string, and then sscanf() to parse/"read" the string into the variables I was interested in.

查看更多
Juvenile、少年°
3楼-- · 2019-05-26 19:56

If scanf() fails to find a matching input, the current variable will be unchanged: check return value of scanf():

/* scanf() returns the number of assignments made.
   In this case, that should be 1. */
if (1 != scanf("%d", &current)) break;

If you wish to continue accepting inputs after an invalid input, the invalid data needs to be read from stdin as it will remain, as pointed out by pmg in the comments. One possible way would be to use the format specifier "%*s" that reads the input but performs no assignment:

if (1 != scanf("%d", &current))
{
    scanf("%*s");
}
else
{
}
查看更多
登录 后发表回答