首页 > 解决方案 > 如果输入了非数字,为什么这个循环会永远循环,但是对于超出范围的数字却可以正常工作

问题描述

我是 c 新手,我不明白为什么输入非数字字符或数字的结果如此不同。解决方法是什么?我在做什么错/不理解?

while ((scanf(" %d", &option) != 1) /* non-numeric input */
       || (option < 0)              /* number too small */
       || (option > 4))             /* number too large */
{
    fflush(stdin); /* clear bad data from buffer */
    printf("That selection isn't valid. Please try again.\n");
    printf("Please enter your choice:  ");
}

数字超出范围的输出(正确):

Please enter your choice: 5
That selection isn't valid. Please try again.

非数字的输出(无限循环):

...
Please enter your choice:  That selection isn't valid. Please try again.
Please enter your choice:  That selection isn't valid. Please try again.
Please enter your choice:  That selection isn't valid. Please try again.
Please enter your choice:  That selection isn't valid. Please try again.
Please enter your choice:  That selection isn't valid. Please try again.
...

修复参考(使用 fgets() 而不是 fflush()):

while ((scanf(" %d", &option) != 1) /* non-numeric input */
       || (option_text[0] < 0)      /* number too small */
       || (option_text[0] > 4))     /* number too large */
{
    fgets(option_text, sizeof(option_text), stdin); 
    printf("That selection isn't valid. Please try again.\n");
    printf("Please enter your choice:  ");
}

标签: cwhile-loopscanf

解决方案


推荐阅读