我正在编写一个程序,在这个程序中,我使用cin>>iUserSel;
从用户那里获得一个整数输入。如果用户输入一个字母,程序就会进入无限循环。我试着用下面的代码来防止这种情况,但程序进入无限循环并打印出“Enter!Enter a #!”。我如何修复我的程序?
cin>>iUserSel;
while (iValid == 1)
{
if (cin.fail())
{
cin.ignore();
cout<<"Wrong! Enter a #!"<<endl;
cin>>iUserSel;
}//closes if
else
iValid = 0;
}//closes while
我在Correct way to use cin.fail()和C++ cin.fail() question上找到了一些关于这方面的信息,但我不知道如何使用它们来解决我的问题。
发布于 2015-10-22 23:19:56
当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');
以防用户输入一个以上的字母。
发布于 2015-10-22 23:20:58
您遇到的问题是您没有从流中清除failbit
。这是通过clear
函数完成的。
在某种程度上相关的注释中,您实际上根本不需要使用fail
函数,而是依赖于输入操作符函数返回流的事实,并且流可以在boolean conditions中使用,那么您可以执行类似以下(未经测试的)代码的操作:
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: ";
}
发布于 2015-10-22 23:23:34
以下是我的建议:
// 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;
}
https://stackoverflow.com/questions/33284483
复制相似问题