C++使用带有boost :: lexical_cast的类

Kia*_*ver 8 c++ boost lexical-cast

我想用我的Testboost::lexical_cast.我已经过载operator<<operator>>,但它给了我运行时错误.
这是我的代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

bad lexical cast: source type value could not be interpreted as target
Run Code Online (Sandbox Code Playgroud)

顺便说一句,我正在使用Visual Studio 2010但我已经尝试使用g ++的Fedora 16并得到了相同的结果!

Luc*_*lle 7

您的问题来自于boost::lexical_cast不忽略输入中的空格(它取消skipws设置输入流的标志)的事实.

解决方案是在提取运算符中自己设置标志,或者只跳过一个字符.实际上,提取操作符应该镜像插入操作符:由于在输出Test实例时明确地放置了空格,因此在提取实例时应该明确地读取空格.

该主题讨论了主题,建议的解决方案是执行以下操作:

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;
} 
Run Code Online (Sandbox Code Playgroud)