重置流的状态

Resetting the State of a Stream

本文关键字:状态      更新时间:2023-10-16

>我有一个问题,与堆栈溢出 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;
}

这里的代码

std::cin.clear(std::istream::failbit);

实际上并没有清除故障位,它会用failbit替换流的当前状态。

要清除所有位,只需调用 clear()

<小时 />

标准中的描述有点复杂,说明为其他功能的结果

void clear(iostate state = goodbit);

后置条件:如果rdbuf()!=0state == rdstate();否则rdstate()==(state | ios_base::badbit)

这基本上意味着下一次调用rdstate()将返回传递给clear()的值。除非存在其他问题,在这种情况下,您也可能会得到badbit

此外,goodbit实际上根本不是位,但值为零以清除所有其他位。

清除一个特定位,您可以使用此调用

cin.clear(cin.rdstate() & ~ios::failbit);

但是,如果清除一个标志而其他标志仍然存在,则仍然无法从流中读取。所以这种使用是相当有限的。