2009-12-26 5 views
1

std :: stringstream 또는 boost :: lexical_cast와 같은 표준 기술을 사용하여 C++ 클래스를 직렬화하고 싶습니다.문자열 스트림 객체와 호환되는 C++ 클래스를 만드는 방법은 무엇입니까?

예를 들어 Point 객체 (2, 4)가있는 경우 "(2, 4)"로 직렬화하고이 문자열에서 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; 
} 

어떻게 이러한 문제를 해결할 수 있습니까?

답변

5

당신은 기능 std::getline을 사용할 수 있습니다, 전체 라인을 읽을 수 있습니다.
+0

고마워,이 간단한 변경 내 코드를 고정! – StackedCrooked

3

AFAIK, str >> text;은 스트림에서 하나의 "단어"를 읽습니다.

구문 분석이 어렵습니다. 무엇 (안된) 이런 일에 대해 :

char paren; 
str >> paren; 
if (paren != '(') throw ParseError(); // or something... 

int x, y; 
char comma; 
str >> x >> comma >> y; 
if (comma != ',') throw ParseError(); 

str >> paren; 
if (paren != ')') throw ParseError(); 
+0

예, 추출 작업이 공백으로 구분된다 – joshperry

3

이미 부스트를 사용하고 있기 때문에, 당신은 왜 먹고 보이지 않는 부스트 serialization?

직렬화 형식은 직렬화되는 개체와 독립적이어야하며 부스트의 lib가이 것을 잘 처리합니다.

std::string text; 
getline(str, text); 
관련 문제