重置流的状态 [英] Resetting the State of a Stream
问题描述
我有一个问题,在这个问题上稍微类似于stackoverflow std :: cin.clear()无法恢复良好状态的输入流,但是提供的答案不适用于我。
I have a question which is slightly similar to this question on stackoverflow std::cin.clear() fails to restore input stream in a good state, but the answer provided there does not work for me.
问题是:如何重置一个流的状态为好?
The question is: how can I reset the state of a stream to 'good' again?
这是我的代码如何尝试,从来没有设置好。
Here is my code how I try it, but the state is never set to good again. I used both of the lines ignore separately.
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;
}
推荐答案
>
The code here
std::cin.clear(std::istream::failbit);
实际上不会清除失败位,它会取代当前状态
doesn't actually clear the failbit, it replaces the current state of the stream with failbit
.
要清除所有位,只需调用 clear
。
To clear all the bits, just call clear()
.
标准中的描述是一个复杂的,函数
The description in the standard is a but convoluted, stated as the result of other functions
void clear(iostate state = goodbit);
后置条件:如果 rdbuf()!= 0
then state == rdstate ();
否则 rdstate()==(state | ios_base :: badbit)
。
Postcondition: If rdbuf()!=0
then state == rdstate();
otherwise rdstate()==(state | ios_base::badbit)
.
这基本上意味着下一次调用 rdstate()
将返回传递给 clear()
。除了有其他一些问题,在这种情况下你也可能得到一个 badbit
。
Which basically means that the next call to rdstate()
will return the value passed to clear()
. Except when there are some other problems, in which case you might get a badbit
as well.
清除<
cin.clear(cin.rdstate() & ~ios::failbit);
但是,如果清除一个标志,而其他标志仍保留,您仍然无法从流中读取。所以这种使用是相当有限的。
However, if you clear one flag and others remain, you still cannot read from the stream. So this use is rather limited.
这篇关于重置流的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!