【发布时间】:2012-06-30 02:38:24
【问题描述】:
我有一个问题与 stackoverflow std::cin.clear() fails to restore input stream in a good state 上的这个问题有点相似,但那里提供的答案对我不起作用。
问题是:如何将流的状态再次重置为“良好”?
这是我尝试的代码,但状态永远不会再次设置为良好。我分别使用了两行忽略。
int _tmain(int argc, _TCHAR* argv[])
{
int result;
while ( std::cin.good() )
{
std::cout << "Choose a number: ";
std::cin >> result;
// Check if input is valid
if (std::cin.bad())
{
throw std::runtime_error("IO stream corrupted");
}
else if (std::cin.fail())
{
std::cerr << "Invalid input: input must be a number." << std::endl;
std::cin.clear(std::istream::failbit);
std::cin.ignore();
std::cin.ignore(INT_MAX,'\n');
continue;
}
else
{
std::cout << "You input the number: " << result << std::endl;
}
}
return 0;
}
【问题讨论】:
标签: c++ state iostream conditional-statements