Gabriel Schreiber Gabriel Schreiber - 2 months ago 12
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 (!in.fail())
c = Coordinate(x, y);

return in;
}


How would you read the delimiter?

Answer

How about let the stream pick commas as your format:

std::istream& comma(std::istream& in)
{
    if ((in >> std::ws).peek() == ',')
        in.ignore();
    else
        in.setstate(std::ios_base::failbit);
    return in;
}

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

in >> x >> comma >> y;