我有一个问题,它与此问题在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;
}
在我的书中说:clear(flag)将指定的条件状态设置为有效。我将其解释为:清除指定的错误位。这是不正确的呢? – physicalattraction
这只是清除()清除*所有*标志。清除单个标志有点复杂(并且不太有用)。我在答复中增加了新的部分。 –