-->

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

2019-05-07 16:56发布

问题:

I was looking into this question and I have no problem understanding the two answers given to it. But I'm not sure I understood the s.clear(ios::badbit); in the statement highlighted below with the comment // set state. For instance, why not s.clear(ios::failbit); instead?

#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;
} 

回答1:

The book you're quoting was published in 1991, 7 years before the first ISO C++ standard was even published. It's not clear why the author chose to use ios::badbit because no rationale was provided in either the 2nd or 3rd editions of the book.

In C++98, a non-member overload for operator>> was added for complex. This mandates that failbit is required to be set in the case of bad input rather than 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).



回答2:

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

std::ios::failbit is intended for recoverable errors. How do you recover from an input stream that is supposed to contain a pair of numbers separated by a comma and enclosed in parentheses after you've already read up to and including the comma?

You might be able to do that, but that would entail somehow backing up (backing up to where?) using tellg and seekg -- and then what? There is no recovery, so setting the badbit is the right thing to do.



标签: c++ istream