c++ if(!cin)导致循环
C++ if(!cin) causes loop
我尝试使用if(!cin)来验证用户输入是否真的是整数。然后我的程序就进入了一个无限循环从来没有要求新的输入
do{
cin >> temp->data;
if(!cin){
cout << "Please enter a Number!" << 'n';
correct=false;
}
}while(correct==false);
如果有人能帮我就太好了:)
当std::cin读取输入失败时,将设置相应的错误标志。因此,您需要使用std::cin.clear()重置标志,以便下一个输入操作能够正常工作,然后使用std::cin.ignore(.)跳过所有内容,直到新行,以避免类似的格式化输入。
while (!(std::cin >> temp->data))
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
std::cout << "nPlease enter a number!" << std::endl;
}
std::numeric_limits<std::streamsize>::max()
返回一个流可以容纳的最大字符数,从而保证忽略整行。
如果您想做这种检查,请将数据从cin
读取到string
并将string
转换为数字:
string str;
do{
cin >> str;
if(!cin){
cout << "Please enter a Number!" << 'n';
correct=false;
}
else{
istringstream stream(str);
stream >> temp->data;
if(!stream){
cout << "Please enter a Number!" << 'n';
correct=false;
}
}
}while(correct==false);
使用cin.fail()
检查用户输入是否正确。如果最后一个cin
命令失败,cin.fail()
返回true
,否则返回false
。此外,您的循环可能是无限的,因此您还必须声明一个else
,将检查标志correct
设置为true
。因此,要使循环的条件无效并在用户输入正确输入的情况下退出循环(参见下面的代码):
do{
cin >> temp->data;
if(cin.fail()){
cin.clear();
cin.ignore(10000, 'n');
cout << "Please enter a Number!" << 'n';
correct=false;
} else {
correct=true;
}
}while(correct==false);
你的'正确'变量实际上不做任何你正在使用它的方式。如果correct
不为真,则不可能退出循环;所以你可以去掉它,当你读到数字时,只使用一个循环退出命令。
而且,到目前为止发布的答案都没有处理正在关闭的输入。在这种情况下,它们会进入一个无限循环。
// A loop; we will break out when we successfully read a number.
while ( 1 )
{
// Prompt for a number and read it
cout << "Please enter a Number!" << endl;
cin >> temp->data;
// Exit loop if we successfully read
if ( cin )
break;
// Check to see if we failed due to the input being closed
if ( cin.eof() )
{
cerr << "End of input reached.n";
return 0; // depends what your function returns of course
}
// reset the error condition that was caused by trying to read an integer and failing
cin.clear();
// discard anything they previously typed
cin.ignore(numeric_limits<streamsize>::max(), 'n');
}
从这里开始,一个好的设计应该是让这个代码本身成为一个完整的函数。然后,您可以在需要安全地获取数字时调用该函数,而无需重复代码。函数声明可以是:
void input_number(int &the_number, std::istream &in, std::string prompt);
将输出the_number
,并且它将通过抛出异常或依靠调用者检查!cin
甚至返回bool
来处理文件结束;
例如,如果在if
语句的条件前放置" !
"。这应该是一个非操作符
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 在 std::getline 和 std::cin 期间卡在循环中
- C++ cin.ignore() 跳过循环
- 而循环跳过 cin.getline() 对于 C 字符串
- 当输入在带有空格的单行中给出时,cin 如何在 while 循环中工作?
- :CIN 不断打印用户在每次循环后输入的内容
- 输入 ctrl + x 后如何再次 cin (cin<<x) 循环(cin 一个结构)
- cin语句在循环的第三次迭代中被跳过
- 在循环中使用 cin.get() 输入字符串
- C++向量:在循环中使用CIN初始化
- 当我输入一个字母时,cin 输入(输入是一个 int),而不是打印错误一次,它打印正确一次,然后在循环的其余部分打印 i
- 为什么cin.rdbuf()->sbumpc()在循环中只要求我输入一次?
- 在 for 循环中使用后,Cin 被跳过
- 如何在我的代码中修复无穷循环?我认为它跳过了第二个CIN,因此它一直在循环
- C :在(CIN)循环中,有时会忽略循环
- 如果 (!(cin >>变量名称)) 在此循环中
- CIN 到矢量输入循环无限期.为什么
- C++ if(cin>>input) 在 while 循环中无法正常工作
- std::cin 导致无限循环
- 我可以做一个循环,直到“std::cin”在输入缓冲区中看到“”字符