std :: cin.clear()无法以良好状态还原输入流 [英] std::cin.clear() fails to restore input stream in a good state
本文介绍了std :: cin.clear()无法以良好状态还原输入流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为了测试bool I/o,我尝试运行以下简短程序:
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;
}
这是我得到的输出:
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)
我想知道为什么输入"t"时会出现无限循环,以及如何防止它发生.
I wonder why I get an infinite loop when I enter 't', and how to prevent it.
谢谢.
推荐答案
清除cin后添加此行:
Add this line after clearing cin:
std::cin.ignore();
这样,流将忽略其缓冲区上剩下的任何内容.
This way, the stream ignores whatever is left on its buffer.
这篇关于std :: cin.clear()无法以良好状态还原输入流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文