Why does while (true) skip cin when it received invalid input? [duplicate]

霸气de小男生 提交于 2021-02-05 08:47:27

问题


This while-loop does not wait for input from cin after receiving wrong input (non-integer). Does cin somehow stay in a false state?

while (true) {
    int x {0};
    cout << "> ";
    cin >> x;
    cout << "= " << x << endl;
}

I would expect this while-loop to wait for input everytime around, but that no longer happens when it receives wrong input.


回答1:


Once cin fails, it stays in an invalid state until it's cleared.

clear() without arguments can be used to unset the failbit after unexpected input

Sets the stream error state flags by assigning them the value of state. By default, assigns std::ios_base::goodbit which has the effect of clearing all error state flags.

As @Peter points out, you also have to clear the buffer.

Your example would be like this:

while (true) {
  int x{0};
  cout << "> ";
  if (!cin) {
    // unset failbit
    cin.clear();
    // clear the buffer
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
  }
  cin >> x;
  cout << "= " << x << endl;
}


来源:https://stackoverflow.com/questions/56303342/why-does-while-true-skip-cin-when-it-received-invalid-input

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!