Resetting cin stream state C++

后端 未结 3 980
说谎
说谎 2020-12-04 01:17

Here Im trying to get an integer from user, looping while the input is correct.

After entering non integer value (e.g \"dsdfgsdg\") cin.fail() returns true, as expec

相关标签:
3条回答
  • 2020-12-04 01:26

    cin.clear() does not clear the buffer; it resets the error flags. So you will still have the sting you entered in your buffer and the code will not allow you to enter new data until you clear the cin buffer. cin.Ignore() should do the trick

    0 讨论(0)
  • 2020-12-04 01:27

    As a matter of style, prefer this method:

    int main() 
    {
        int a;
        while (!(std::cin >> a))
        {
            std::cout << "Incorrect data. Enter new integer:" << std::endl;
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        }
    }
    
    0 讨论(0)
  • 2020-12-04 01:28

    After cin.clear(), you do this:

    #include <iostream> //std::streamsize, std::cin
    #include <limits> //std::numeric_limits
    ....
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')
    

    What the above does is that it clears the input stream of any characters that are still left there. Otherwise cin will continue trying to read the same characters and failing

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