int 变量中的循环和字符无法按我的预期工作
我在这段代码中看到了一个不寻常的问题:
#include <iostream>
using namespace std;
int main()
{
int number;
bool repeat=true;
while (repeat)
{
cout<<"\nEnter a number:";
cin>>number;
cout<<"\nNumber is:"
<<number;
cout<<"\nRepeat?:";
cin>>repeat;
}
system("pause");
return 0;
}
在这段代码中,当我将一个字符这样的“A”放入int类型变量while循环重复时一遍又一遍,不要问我是否重复。 当我输入字符而不是整数时,就会出现此问题。 这也与 for 一起出现。
为什么会发生这种事? 谢谢
i saw an unusual problem in this code:
#include <iostream>
using namespace std;
int main()
{
int number;
bool repeat=true;
while (repeat)
{
cout<<"\nEnter a number:";
cin>>number;
cout<<"\nNumber is:"
<<number;
cout<<"\nRepeat?:";
cin>>repeat;
}
system("pause");
return 0;
}
here in this code when i put a character such "A" in int type variable while loop repeats over and over and don't ask me whether to repeat or not.
this problem just appear when i put characters not integers.
this appears with for too.
why should happen this?
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
读入无法转换的用户输入后,输入流处于无效状态。您需要清空流并调用clear方法重置流上的错误位以恢复正常操作。
如果您检测到输入不成功(使用输入流状态位,可通过
good()
或fail()
等方法访问),您可以使用以下命令重置流类似这样的代码:After reading in user input which cannot be converted, the input stream is in an invalid state. You need to empty the stream and call the
clear
method to reset the error bits on the stream in order to resume normal operation.If you detect that input was not successful (using the input streams state bits, accessible via methods like
good()
orfail()
etc.) you can reset the stream using code similar to this:当您未能从中提取 int 时,您将 cin 置于错误状态,并且无法恢复。因此,当您尝试从中提取重复时,流仍处于失败状态。您需要检查 number 是否失败(只需使用 if(cin >> number))。
You put cin in an error state when you failed to extract an int from it, and didn't recover. So when you then tried to extract repeat from it, the stream is still in a failed state. You need to check for the failure of number (just use if(cin >> number)).