c++ - input errors : split part of one entery -
i doing practice on standard i/o have complex class . class has overloaded insertion , extraction operators ,the input should of form : x + yi(e.g 10 + 9i) have determine if input valid or not . there problem , if input in form result failbit , cause inputing char 'i' integer data type . how can , without having fail bit ? mine function :
istream &operator>>(istream &input, complex &complex) {     input >> complex.realpart;     input.ignore(3);     input >> complex.imaginarypart;      return input; }   but not enough !if there space between , integer solve every thing . there no !i thought of using array , or string,but copying them int private data of class, not seem programming . , errors have after all?? lot ! ;)
you have check '+' , trailing 'i':
istream &operator>>(istream &input, complex &complex) {     char plus,letter;     if (input >> complex.realpart >> plus)  {         if (plus!='+' )              input.setstate(ios::failbit);         else if (input >> complex.imaginarypart>>letter) {              if (letter!='i')                  input.setstate(ios::failbit);         }     }     return input; }   live demo here
note make simpler teh following:
istream &operator>>(istream &input, complex &complex) {     char plus,letter;     if ( (input >> complex.realpart >> plus >> complex.imaginarypart>>letter) && (plus!='+' || letter!='i'))             input.setstate(ios::failbit);     return input; }   the difference previous version when letter plus provided: first version stops read input knowing it's anyway wrong, while second version continue consume stream.
Comments
Post a Comment