如何在c++中正确使用cin.fail()

How to use cin.fail() in c++ properly

本文关键字:cin fail c++      更新时间:2023-10-16

我正在写一个程序,我从用户那里得到一个整数输入与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;
}