Non-numerical input causes endless loop

余生颓废 提交于 2019-12-08 02:15:29

问题


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

回答1:


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
{
}



回答2:


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.



来源:https://stackoverflow.com/questions/11314246/non-numerical-input-causes-endless-loop

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