std::cin.clear() fails to restore input stream in a good state

跟風遠走 提交于 2019-12-04 04:55:19

问题


In order to test bool i/o, I tried to run this short program:

#include <iostream>

int main()
{
 while(true)
 {
  bool f;
  if (std::cin >> f)
   std::cout << f << '\n';
  else
  {
   std::cout << "i/o error\n";
   std::cin.clear();
  }
 }
 return 0;
}

Here is the output I get:

g++ -Wall -ansi -pedantic -o boolio boolio.cpp
./boolio
0
0
1
1
2
i/o error
-
i/o error
t
i/o error
i/o error
i/o error
... (infinite loop)

I wonder why I get an infinite loop when I enter 't', and how to prevent it.

Thanks.


回答1:


Add this line after clearing cin:

std::cin.ignore();

This way, the stream ignores whatever is left on its buffer.




回答2:


Try to use following combo:

cin.ignore(INT_MAX, '\n'); // ignore all characters in the current line

cin.clear(); // restore 'good' flag

Using only cin.ignore() will discard only one character in the buffer.




回答3:


if (std::cin >> f) expects either a 0 or 1. And treats all other values as an I/0 error. Even if you enter '-' or 2, std::cin.ignore() is still needed.

If you want the program to enter only the values true or false, use the following statement instead of (std::cin >> f)

(std::cin >> boolalpha >> f)



来源:https://stackoverflow.com/questions/4960399/stdcin-clear-fails-to-restore-input-stream-in-a-good-state

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