为什么`s.clear(ios :: badbit);`下面?为什么不`s.clear(ios :: failbit);`? [英] Why `s.clear(ios::badbit);` below? Why not `s.clear(ios::failbit);`?
问题描述
我在调查这个问题,我对提供的两个答案没有任何问题。但我不确定我理解了 s.clear(ios :: badbit);
在下面突出显示的语句与 //设置状态
。例如,为什么 s.clear(ios :: failbit);
改为?
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;
}
推荐答案
您引用的书是在1991年发布的,在第一个ISO C ++标准发布之前的7年。不清楚为什么作者选择使用 ios :: badbit
,因为在本书的第2版或第3版中没有提供理由。
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.
在C ++ 98中,为<$ cc添加了 operator>>
的非成员重载$ c> complex 。这要求在输入不正确而不是 badbit
的情况下设置 failbit
。
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
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
.
如果遇到错误输入,则调用 is.setstate(ios: :failbit)
(其中
可以抛出 ios :: failure
(27.4.4.3)。
If bad input is encountered, calls is.setstate(ios::failbit)
(which
may throw ios::failure
(27.4.4.3).
这篇关于为什么`s.clear(ios :: badbit);`下面?为什么不`s.clear(ios :: failbit);`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!