C++ 如何在c++;适当地
我正在编写一个程序,其中我使用C++ 如何在c++;适当地,c++,iostream,C++,Iostream,我正在编写一个程序,其中我使用cin>>iUserSel从用户那里获得一个整数输入。如果用户输入一个字母,程序将进入无限循环。我试图用下面的代码来防止这种情况,但程序进入无限循环并打印出“错误!输入a”。如何修复我的程序 cin>>iUserSel; while (iValid == 1) { if (cin.fail()) { cin.ignore(); cout<<"Wro
cin>>iUserSel从用户那里获得一个整数输入代码>。如果用户输入一个字母,程序将进入无限循环。我试图用下面的代码来防止这种情况,但程序进入无限循环并打印出“错误!输入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
cin>>iUserSel;
while(iValid==1)
{
if(cin.fail())
{
cin.ignore();
cout当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(数值限制::max(),'\n');
如果用户输入多个字母。您遇到的问题是没有从流中清除故障位。这是通过函数完成的
与此相关的一点是,您根本不需要使用fail
函数,而是依赖于输入运算符函数返回流,并且流可以在中使用,然后您可以执行类似于以下(未测试)代码的操作:
while(!(标准:cin>>iUserSel))
{
//清除错误(如failbit标志)
std::cin.clear();
//扔掉剩下的线
std::cin.ignore(std::numeric_limits::max(),'\n');
std::cout以下是我的建议:
// 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;
}
//读取数据并检查读取是否成功。
//如果读取成功,则中断循环。
//否则,进入循环。
而(!(cin>>iUserSel))
{
//如果我们已经到达EOF,循环中断或退出。
if(cin.eof())
{
//出口(0)????
打破
}
//清除流的错误状态。
cin.clear();
//忽略该行的其余部分。
cin.ignore(std::numeric_limits::max(),'\n');
//询问更多新的信息。
不能使用cin.fail()
和iValid
标志来测试代码中的相同状态。这属于编码中的格言“不要重复自己”。在这里,这会导致代码状态管理不当,因为您正在检查“相同”的两个版本在代码中的不同点声明,您会感到困惑。
cin.ignore(numeric_limits<streamsize>::max(), '\n');
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;
}