我现在开始学习 C++,所以我想这将是一个非常简单的新手问题。
那么,为什么 while 内的“cin >> x”行不会停止循环以获取用户输入(如果用户输入字符而不是数字)?
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
int x = 0;
cout << "Please, enter x: ";
cin >> x;
while (!cin)
{
cout << "Please, it must be a number!\n";
cin >> x;
}
cout << "Thanks!.";
cin.ignore();
cin.ignore();
}
我才学习 C++ 两天,所以我完全不知道“cin”到底是什么。我尝试使用“cin.sync()”和“cin.clear()”,但仍然没有运气。
我知道不可能做“cin=true”或“cout
嗯,你的程序应该稍微修正一下
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
int x = 0;
cout << "Please, enter x: ";
cin >> x;
while (!cin)
{
cin.clear();
cin.ignore(10000, '\n');
cout << "Please, it must be a number!" << endl;
cin >> x;
}
cout << "Thanks!.";
}
这样它就可以按预期工作。有关它的更多信息here https://stackoverflow.com/questions/5131647/why-would-we-call-cin-clear-and-cin-ignore-after-reading-input。一般来说,您需要清除 cin 中的所有错误内容。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)