std::cin loops even if I call ignore() and clear()

2020-04-16 04:50发布

I'm trying to setup an input checking loop so it continuously ask the user for a valid (integer) input, but it seems to get trapped in an infinite loop.

I've searched for solutions and tried to ignore() and clear(), but it still doesn't stop.

Could you please correct me where I'm wrong here?

int num;
cin >> num;
while (cin.fail()) {
  cin.ignore();
  cin.clear();
  cout << "Enter valid number: " << endl;
  cin >> num;
}

标签: c++ cin
2条回答
家丑人穷心不美
2楼-- · 2020-04-16 05:14

The ignore() has no effect when the stream is in fail state, so do the clear() first.

查看更多
Summer. ? 凉城
3楼-- · 2020-04-16 05:29

When the stream is in an state of error,

  cin.ignore();

does not do anything. You need to call cin.clear() first before calling cin.ignore().

Also, cin.ignore() will ignore just one character. To ignore a line of input, use:

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

Add

#include <limits>

to be able to use std::numeric_limits.

The fixed up block of code will look something like:

int num;
while ( !(cin >> num) ) {
   cin.clear();
   cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
   cout << "Enter valid number: " << endl;
}
查看更多
登录 后发表回答