相关疑难解决方法(0)

重置流的状态

我有一个与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)

c++ state iostream conditional-statements

7
推荐指数
1
解决办法
9605
查看次数

标签 统计

c++ ×1

conditional-statements ×1

iostream ×1

state ×1