C ++ Using classes with boost :: lexical_cast

I want to use my test class with boost::lexical_cast . I overloaded operator<< and operator>> , but this gives me a runtime error.
Here is my code:

 #include <iostream> #include <boost/lexical_cast.hpp> using namespace std; class Test { int a, b; public: Test() { } Test(const Test &test) { a = test.a; b = test.b; } ~Test() { } void print() { cout << "A = " << a << endl; cout << "B = " << b << endl; } friend istream& operator>> (istream &input, Test &test) { input >> test.a >> test.b; return input; } friend ostream& operator<< (ostream &output, const Test &test) { output << test.a << test.b; return output; } }; int main() { try { Test test = boost::lexical_cast<Test>("10 2"); } catch(std::exception &e) { cout << e.what() << endl; } return 0; } 

Output:

 bad lexical cast: source type value could not be interpreted as target 

Btw I am using Visual Studio 2010 But I tried Fedora 16 with g ++ and got the same result!

+7
source share
1 answer

Your problem is that boost::lexical_cast does not ignore spaces in the input (it disables the skipws flag of the input stream).

The solution is to either set the flag yourself in your extract statement, or simply skip one character. Indeed, the extraction operator should reflect the insertion operator: since you explicitly put a space in the output of the Test instance, you must explicitly read the space in the extraction of the instance.

This thread discusses the topic, and the recommended solution is to do the following:

 friend std::istream& operator>>(std::istream &input, Test &test) { input >> test.a; if((input.flags() & std::ios_base::skipws) == 0) { char whitespace; input >> whitespace; } return input >> test.b; } 
+7
source

All Articles