为什么下面是 `s.clear(ios::badbit);`?为什么不是`s.clear(ios::failbit);`?

Why `s.clear(ios::badbit);` below? Why not `s.clear(ios::failbit);`?

我正在调查 ,我对给出的两个答案的理解没有问题。但我不确定我是否理解下面用评论 // set state 突出显示的声明中的 s.clear(ios::badbit);。例如,为什么不 s.clear(ios::failbit); 而不是?

#include <istream>
#include <complex>

using namespace std;

istream& operator>>(istream& s, complex<double>& a)
{
    // input formats for a complex; "f" indicates a float:
    //
    //   f
    //   (f)
    //   (f, f)

    double re = 0, im = 0;
    char c = 0;

    s >> c;
    if( c == '(' ) {
        s >> re >> c;
        if( c == ',' ) s >> im >> c;
        if( c != ')' ) s.clear(ios::badbit);  // set state
    }
    else {
        s.putback(c);
        s >> re;
    }

    if( s ) a = complex<double>(re, im);
    return s;
} 

For instance, why not s.clear(ios::failbit); instead?

std::ios::failbit 用于可恢复的错误。在您已经阅读并包括逗号之后,您如何从应该包含一对用逗号分隔并括在括号中的数字的输入流中恢复?

您也许可以做到这一点,但这需要以某种方式备份(备份到哪里?)使用 tellgseekg -- 然后呢?没有恢复,所以设置 badbit 是正确的做法。

您引用的这本书出版于 1991 年,比第一个 ISO C++ 标准发布早了 7 年。不清楚为什么作者选择使用 ios::badbit,因为在该书的第 2 版或第 3 版中均未提供基本原理。

在 C++98 中,为 complex 添加了 operator>> 的非成员重载。这要求在输入错误的情况下需要设置 failbit 而不是 badbit.

N1905 26.2/13

template < class T , class charT , class traits >
basic_istream < charT , traits >&
operator > >( basic_istream < charT , traits >& is , complex <T >& x );

Requires: The input values be convertible to T.

If bad input is encountered, calls is.setstate(ios::failbit) (which may throw ios::failure (27.4.4.3).