请阅读以下代码:
#include <iostream>
#include <cstdlib>
int main() {
std::cout << "Please input one integer." << std::endl;
int i;
while (true) {
std::cin >> i;
if (std::cin) {
std::cout << "i = " << i << std::endl;
break;
} else {
std::cout << "Error. Please try again."<< std::endl;
std::cin.ignore();
std::cin.clear();
}
}
std::cout << "Thank you very much." << std::endl;
std::system("pause");
return 0;
}
当我给 std::cin 提供无效输入时,例如 w
,然后Error. Please try again.
是无限输出的。
我以为std::cin.ignore
会将输入流清空,并且 std::cin.clear
会将其恢复到正常状态。那么为什么会出现无限循环呢?
最佳答案
默认情况下,std::basic_istream::ignore()
仅忽略 1 个字符:
basic_istream& ignore( std::streamsize count = 1, int_type delim = Traits::eof() );
(来自 http://en.cppreference.com/w/cpp/io/basic_istream/ignore )
对于您的案例来说,更惯用的用法似乎是示例中的用法:
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
另外,请注意,您要在 ignore()
调用之前调用 clear()
,因此 ignore()
的输入提取将会成功而不是立即返回。
关于c++ - std::cin 来自无效输入的无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38890379/