Вопрос

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?

Это было полезно?

Решение

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;
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top