phy*_*ion 7 c++ state iostream conditional-statements
我有一个与stackoverflow上的这个问题略有相似的问题std :: cin.clear()无法恢复状态良好的输入流,但提供的答案对我不起作用.
问题是:如何将流的状态再次重置为"良好"?
这是我的代码我是如何尝试的,但状态永远不会再次变好.我分别忽略了这两行.
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;
}
Run Code Online (Sandbox Code Playgroud)
Bo *_*son 15
这里的代码
std::cin.clear(std::istream::failbit);
Run Code Online (Sandbox Code Playgroud)
实际上并没有清除failbit,它取代了当前的流状态failbit.
要清除所有位,只需调用即可clear().
标准中的描述有点复杂,作为其他功能的结果
void clear(iostate state = goodbit);后置条件:如果
rdbuf()!=0再state == rdstate();不然rdstate()==(state | ios_base::badbit).
这基本上意味着下一次调用rdstate()将返回传递给的值clear().除非有其他问题,在这种情况下你也可以得到一个badbit.
而且,goodbit实际上根本不是一点,但是值为零以清除所有其他位.
要仅清除一个特定位,您可以使用此调用
cin.clear(cin.rdstate() & ~ios::failbit);
Run Code Online (Sandbox Code Playgroud)
但是,如果清除一个标志而其他标志仍然存在,则仍然无法从流中读取.所以这种用途相当有限.