C ++ if(!cin)导致循环 [英] C++ if(!cin) causes loop
问题描述
我尝试使用if(!cin)来验证用户输入是否确实是整数。但是,我的程序然后进入了一个无限循环,从未询问过新输入
I tried to use if(!cin) to validate if the user input really is an integer. However my programm then just goes into an infinite loop never asking vor new input
do{
cin >> temp->data;
if(!cin){
cout << "Please enter a Number!" << '\n';
correct=false;
}
}while(correct==false);
如果有人可以帮助我,那将很棒:)
Would be great if someone could help me :)
推荐答案
当std :: cin无法读取输入时,将设置适当的错误标志。因此,您想使用std :: cin.clear()重置标志,以便下一个输入操作将正常工作,然后使用std :: cin.ignore(..)跳过所有内容,直到新行,以免格式类似输入。
When std::cin fails to read the input, the appropriate error flags are set. Therefore you want to reset the flags using std::cin.clear() so that the next input operation will work correctly and then skip everything until the new line using std::cin.ignore(..) in order to avoid similarly formatted input.
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()
返回流可以容纳的最大字符数,从而确保整行都被忽略。
std::numeric_limits<std::streamsize>::max()
returns the max amount of characters a stream can hold so that the whole line is guaranteed to be ignored.
这篇关于C ++ if(!cin)导致循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!