c - 如果输入了非数字,为什么这个循环会永远循环,但是对于超出范围的数字却可以正常工作
问题描述
我是 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: ");
}
解决方案
推荐阅读
- reactjs - 如何使用从 Java API 检索的数据呈现数据表组件来解决此问题?
- c# - 主键盘上 Enter 键的虚拟键码是什么?
- vert.x - 通过 Eclipse 运行 Vert.x (w/ES4X)
- numpy - 没有显式数组的二进制搜索
- java - 从 chrome 自定义选项卡获取下载回调
- linux - 使用 conda-build 创建包时如何精确 Perl 版本
- c# - 带有数据注释 MVC 的数据读取器 EF 6 不正确
- datacontext - 如何从另一个视图模型访问公共变量
- c++ - 缩小png字体
- java - 如何修复 java.security.InvalidAlgorithmParameterException:连接到 elasticsearch 时 trustAnchors 参数必须非空