[英]How to use cin.fail() in c++ properly
我正在编写一个程序,通过cin>>iUserSel;
从用户那里获得一个整数输入cin>>iUserSel;
. 如果用户输入一个字母,程序就会进入无限循环。 我试图用下面的代码防止这种情况发生,但程序进入无限循环并打印出“错误!输入#!”。 如何修复我的程序?
cin>>iUserSel;
while (iValid == 1)
{
if (cin.fail())
{
cin.ignore();
cout<<"Wrong! Enter a #!"<<endl;
cin>>iUserSel;
}//closes if
else
iValid = 0;
}//closes while
我在使用 cin.fail()和C++ cin.fail() 问题的正确方法中找到了一些关于此的信息,但我不明白如何使用它们来解决我的问题。
当cin
失败时,需要清除错误标志。 否则后续的输入操作将是非操作。
要清除错误标志,您需要调用cin.clear()
。
您的代码将变为:
cin >> iUserSel;
while (iValid == 1)
{
if (cin.fail())
{
cin.clear(); // clears error flags
cin.ignore();
cout << "Wrong! Enter a #!" << endl;
cin >> iUserSel;
}//closes if
else
iValid = 0;
}//closes while
我也建议你改变
cin.ignore();
到
cin.ignore(numeric_limits<streamsize>::max(), '\n');
如果用户输入多个字母。
您遇到的问题是您没有从流中清除failbit
。 这是通过clear
函数完成的。
在有些相关的说明中,您根本不需要使用fail
函数,而是依赖于输入运算符函数返回流的事实,并且该流可以在布尔条件中使用,然后您可以执行类似的操作以下(未经测试)代码:
while (!(std::cin >> iUserSel))
{
// Clear errors (like the failbit flag)
std::cin.clear();
// Throw away the rest of the line
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Wrong input, please enter a number: ";
}
以下是我的建议:
// Read the data and check whether read was successful.
// If read was successful, break out of the loop.
// Otherwise, enter the loop.
while ( !(cin >> iUserSel) )
{
// If we have reached EOF, break of the loop or exit.
if ( cin.eof() )
{
// exit(0); ????
break;
}
// Clear the error state of the stream.
cin.clear();
// Ignore rest of the line.
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// Ask more fresh input.
cout << "Wrong! Enter a #!" << endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.