【问题标题】:How to use cin.fail() in c++ properly如何在 C++ 中正确使用 cin.fail()
【发布时间】:2015-10-22 15:12:56
【问题描述】:

我正在编写一个程序,在该程序中,我使用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

我在Correct way to use cin.fail()C++ cin.fail() question 找到了一些相关信息 ,但我不明白如何使用它们来解决我的问题。

【问题讨论】:

  • 不要使用cin.fail()iValid 标志来测试代码中的相同状态。它属于编码中“不要重复自己”的格言。在这里,它会导致您对代码的状态管理不善,因为您在代码的不同点检查“相同”状态的两个版本,您会感到困惑。

标签: c++ iostream


【解决方案1】:

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'); 

如果用户输入多个字母。

【讨论】:

    【解决方案2】:

    您遇到的问题是您没有清除流中的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: ";
    }
    

    【讨论】:

      【解决方案3】:

      以下是我的建议:

      // 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;
      }
      

      【讨论】:

        猜你喜欢
        • 2013-07-29
        • 2021-07-16
        • 2020-08-26
        • 2013-08-26
        • 2015-07-12
        • 2013-04-10
        相关资源
        最近更新 更多