This is an example extracted from section 10.3.3. Entering custom types from the book "C ++ Programming Language", second edition, B. Stroustrup. The code is old, but still compiles with minor changes. Example:
#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; } Despite the lack of error handling code, this will actually be the majority of types of errors. The local variable is cinitialized in order to avoid after the emergency operation << 22> the value of the'(' final check of the flow state ensures that the value of the argument achanges if everything goes well.
#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; }
Despite the lack of error handling code, this will actually be the majority of types of errors. The local variable is cinitialized in order to avoid after the emergency operation << 22> the value of the'(' final check of the flow state ensures that the value of the argument achanges if everything goes well.
c
'('
a
I could not understand the phrase underlined above.
s >> c , c .
s >> c
c , if( c == '(' ). char undefined.
if( c == '(' )
char
undefined.
char c = 0; , s.putback(c); , s good(). , :
char c = 0;
s.putback(c);
s
good()
char c; s >> c; if ( !s ) return s;
, , , ; , , .
, , c:
char c; s >> c; if (c == '(') { ... }
, >> . , c == '(', :
>>
c == '('
istream
c 0, 2 : , , c 0... , '(' istream.
0