[Univ of Cambridge] [Dept of Engineering]
next up previous contents
Next: String streams Up: Input/Output Previous: Output of User-Defined types

Input of User-Defined types

The following code reads in a complex number that's provided in the form (a,b) or (a)

istream& operator>>(istream&s, complex &a) // returns istream& so can be chained
{
 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_base::badbit);

 }
 else {
   s.putback(c);
   s>> re;
 }

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



Tim Love
2001-07-05