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; }
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 forcomplex
. This mandates thatfailbit
is required to be set in the case of bad input rather thanbadbit
.N1905 26.2/13
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
andseekg
-- and then what? There is no recovery, so setting thebadbit
is the right thing to do.