本文介绍了为什么下面的c ++代码保持输出“坏数据,再试一次”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int main()
{
        int temp;
        while (cin>>temp, !cin.eof())
        {
                if (cin.bad())
                {
                        throw runtime_error("IO stream corrupted");
                }

                if (cin.fail())
                {
                        cerr<<"bad data, try again";
                        cin.clear(istream::failbit);
                        continue;
                }
        }

        return 0;
}



如果输入 x 然后输入,输出将是:

为什么? >

Why?

推荐答案

方法实际上用其参数替换流控制状态位。您每次发出 cin.clear时将 cin 的控制状态设置为 fail (istream :: failbit);

The ios::clear() method actually replaces the stream control state bits with its argument. You're setting cin's control state to fail every time you issue cin.clear(istream::failbit);.

你应该简单地调用 cin.clear(); 而不是参数。这会将流的控制状态重置为

You should simply call cin.clear(); instead, without arguments. That will reset the stream's control state to good.

编辑: ,我忘了。

您还需要调用丢弃您刚才输入的无效 x 令牌,因为 clear 不会冲刷待处理的输入:

You also need to call istream::ignore() to discard the invalid x token you've just entered, since clear() doesn't flush pending input:

if (cin.fail()) {
    cerr << "bad data, try again\n";
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    continue;
}

这篇关于为什么下面的c ++代码保持输出“坏数据,再试一次”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 12:12