如何使C++类与stringstream对象兼容?

Sta*_*ked 1 c++

我想能够使用标准的技术,如性病:: stringstream的连载我的C++类或升压:: lexical_cast的.

例如,如果我有一个Point对象(2,4),那么我想将它序列化为"(2,4)",并且还能够从该字符串构造一个Point对象.

我已经有一些代码,但有一些问题.指向字符串有效,但有时输入未完全从流中读取.Point转换的字符串会导致bad_cast异常.

class Point
{
public:
    Point() : mX(0), mY(0) {}
    Point(int x, int y) : mX(x), mY(y){}
    int x() const { return mX; }
    int y() const { return mY; }
private:
    int mX, mY;
};

std::istream& operator>>(std::istream& str, Point & outPoint)
{
    std::string text;
    str >> text; // doesn't always read the entire text
    int x(0), y(0);
    sscanf(text.c_str(), "(%d, %d)", &x, &y);
    outPoint = Point(x, y);
    return str;
}

std::ostream& operator<<(std::ostream& str, const Point & inPoint)
{
    str << "(" << inPoint.x() << ", " << inPoint.y() << ")";
    return str;
}

int main()
{   
    Point p(12, 14);    
    std::string ps = boost::lexical_cast<std::string>(p); // "(12, 14)" => OK    
    Point p2 = boost::lexical_cast<Point>(ps); // throws bad_cast exception!
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我该如何解决这些问题?

R S*_*hko 5

要读取整行,可以使用函数std :: getline:

std::string text;
getline(str, text);
Run Code Online (Sandbox Code Playgroud)