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

安稳与你 提交于 2019-12-29 07:12:28

问题


I'm writing a program where I get an integer input from the user with cin>>iUserSel;. If the user puts in a letter, the program goes to an infinite loop. I tried to prevent that with the code below, but the program goes to an infinite loop and prints out "Wrong! Enter a #!". How can I fix my program?

cin>>iUserSel;
while (iValid == 1)
{
        if (cin.fail())
        {
                cin.ignore();
                cout<<"Wrong! Enter a #!"<<endl;
                cin>>iUserSel;
        }//closes if
        else
                iValid = 0;
}//closes while

I found some information on this at Correct way to use cin.fail() and C++ cin.fail() question , but I didn't understand how to use them to fix my issue.


回答1:


after cin fails you need to clear the error flag otherwise any other input operation will be a non op. To clear the error flags you need to call cin.clear(). Your code would then become

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

I would also suggest you change cin.ignore(); to cin.ignore(numeric_limits<streamsize>::max(), '\n'); in case the user enters more than 1 letter.




回答2:


The problem you are having is that you don't clear the failbit from the stream. This is done with the clear function.


On a somewhat related note, you don't really need to use the fail function at all, instead rely of the fact that the input operator function returns the stream, and that streams can be used in boolean conditions, then you could do something like the following (untested) code:

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:


Here's what I would recommend:

// 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/how-to-use-cin-fail-in-c-properly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!