Resseting cin stream state c++

2020-02-06 17:28发布

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 expected and while loop body starts executing.

Here I reset error flags of cin, using cin.clear(); and cin.fail() returns false, as expected.

But next call to cin doesn't work and sets error flags back on.

Any ideas?

#include<iostream>
using namespace std;

int main() {
  int a;
  cin >> a;

  while (cin.fail()) {
    cout << "Incorrect data. Enter new integer:\n";
    cin.clear();
    cin >> a;
  }
} 

3条回答
虎瘦雄心在
2楼-- · 2020-02-06 17:45

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');
    }
}
查看更多
家丑人穷心不美
3楼-- · 2020-02-06 17:56

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

查看更多
叛逆
4楼-- · 2020-02-06 17:59

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

查看更多
登录 后发表回答