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

后端 未结 3 1403
故里飘歌
故里飘歌 2020-12-09 23:32

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.

相关标签:
3条回答
  • 2020-12-10 00:08

    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;
    }
    
    0 讨论(0)
  • 2020-12-10 00:10

    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: ";
    }
    
    0 讨论(0)
  • 2020-12-10 00:32

    When cin fails, you need to clear the error flag. Otherwise subsequent input operations 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 one letter.

    0 讨论(0)
提交回复
热议问题