[英]When using a while loop to traverse a linked list, why does my loop iterate by twice the number of nodes in the list?
[英]why does my int while loop keeps going when i scan for a number?
我在while循环中遇到问题。 我必须输入一个大于0且小于81的数字。当我使用-1,0,1,2,82之类的数字时,它会变好并得到预期的结果,但是当我使用字母时,它会继续通过我的while循环。 我在eclipse中使用了调试器,当我处于while循环时,由于scanf失败,循环amount
自动设置为“ 0”。 为什么插入字母时它会不断循环播放?
#include <stdio.h>
#include <stdlib.h>
int main(){
int amount = 0;
printf("Give a number:\n");
fflush(stdout);
scanf("%d",&amount);
while(amount <= 0 || amount >= 81){
printf("Wrong input try again.\n");
printf("Give a number:\n");
fflush(stdout);
scanf("%d",&amount);
}
return EXIT_SUCCESS;
}
您需要确保scanf()
有效。 使用返回值执行此操作
if (scanf("%d", &amount) != 1) /* error */;
当它不起作用时(例如在输入中找到一个字母),您可能想摆脱错误的原因。
从用户那里获取输入的更好的选择是使用fgets()
看到这个相关的问题: scanf()不等待用户输入
原因是当您按Enter键并输入一个字符时,scanf失败,并且没有吞噬输入提要中的字符。 结果,下一个块开始具有您之前输入的内容。
您可以通过在while
循环中的scanf()
之前添加getchar()
来进行检查。 您会注意到,它会重复while循环,直到您的行中包含无效字符为止,然后停止并等待输入。 每次循环运行时, getchar()
在输入中使用无效字符之一。
不过,最好不要使用scanf
这样的。 看看这个资源: 用scanf()读一行不好吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.