[英]why does my int while loop keeps going when i scan for a number?
I'm having a problem with a while loop. 我在while循环中遇到问题。 I have to enter a number which is bigger than 0 and below 81. when I use numbers like -1,0,1,2,82 it is going good and I get the expected result, but when I use a letter it keeps going through my while loop.
我必须输入一个大于0且小于81的数字。当我使用-1,0,1,2,82之类的数字时,它会变好并得到预期的结果,但是当我使用字母时,它会继续通过我的while循环。 I've used the debugger in eclipse and when I'm at the while loop
amount
is automatically set to '0' because of the failed scanf. 我在eclipse中使用了调试器,当我处于while循环时,由于scanf失败,循环
amount
自动设置为“ 0”。 Why does it keep looping when I insert a letter? 为什么插入字母时它会不断循环播放?
#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;
}
You need to make sure the scanf()
worked. 您需要确保
scanf()
有效。 Use the returned value to do that 使用返回值执行此操作
if (scanf("%d", &amount) != 1) /* error */;
When it doesn't work (because eg a letter was found in input) you probably want to get rid of the cause of the error. 当它不起作用时(例如在输入中找到一个字母),您可能想摆脱错误的原因。
A better option to get input from users is to use fgets()
从用户那里获取输入的更好的选择是使用
fgets()
See this related question: scanf() is not waiting for user input 看到这个相关的问题: scanf()不等待用户输入
The reason is that when you press enter with a char, scanf failed and didn't eat up the char in the input feed. 原因是当您按Enter键并输入一个字符时,scanf失败,并且没有吞噬输入提要中的字符。 As a result, the next block begins having whatever you entered before.
结果,下一个块开始具有您之前输入的内容。
You can check that by adding a getchar()
before the scanf()
inside the while
loop. 您可以通过在
while
循环中的scanf()
之前添加getchar()
来进行检查。 You'll notice that it'll repeat the while loop as many times as your line has invalid characters, then stop and wait for input. 您会注意到,它会重复while循环,直到您的行中包含无效字符为止,然后停止并等待输入。 The
getchar()
ate one of the invalid chars in the input each time the loop ran. 每次循环运行时,
getchar()
在输入中使用无效字符之一。
It would be better not to use scanf
like that, though. 不过,最好不要使用
scanf
这样的。 Take a look a this resource: Reading a line using scanf() not good? 看看这个资源: 用scanf()读一行不好吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.