Gabriel Schreiber Gabriel Schreiber - 1 month ago 5
C++ Question

Reading custom coordinate class from istream

I have a custom Coordinate class and want to overload the operator>> for it.
I'm not sure what's the proper way to do this.

A valid stream representation for the coordinates is two comma-separated integers with whitespaces allowed inbetween (eg. " -3 ,4 " or "55 , 7" or "1,2".

Code so far is:

inline std::istream& operator>> (std::istream& in, Coordinate& c)
Coordinate::coord_type x; // int
Coordinate::coord_type y;
in >> x;
// read comma
in >> y;
if (!
c = Coordinate(x, y);

return in;

How would you read the delimiter?


How about let the stream pick commas as your format:

std::istream& comma(std::istream& in)
    if ((in >> std::ws).peek() == ',')
    return in;

then you can read commas among your data, just like below:

in >> x >> comma >> y;