简体   繁体   English

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

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

I'm writing a program where I get an integer input from the user with cin>>iUserSel;我正在编写一个程序,通过cin>>iUserSel;从用户那里获得一个整数输入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() andC++ cin.fail() question , but I didn't understand how to use them to fix my issue.我在使用 cin.fail()C++ cin.fail() 问题的正确方法中找到了一些关于此的信息,但我不明白如何使用它们来解决我的问题。

When cin fails, you need to clear the error flag.cin失败时,需要清除错误标志。 Otherwise subsequent input operations will be a non op.否则后续的输入操作将是非操作。

To clear the error flags, you need to call cin.clear() .要清除错误标志,您需要调用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 one letter.如果用户输入多个字母。

The problem you are having is that you don't clear the failbit from the stream.您遇到的问题是您没有从流中清除failbit This is done with the clear function.这是通过clear函数完成的。


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:在有些相关的说明中,您根本不需要使用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: ";
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM