C使用带有boost :: lexical_cast的类

前端之家收集整理的这篇文章主要介绍了C使用带有boost :: lexical_cast的类前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在boost :: lexical_cast中使用我的Test类.我有重载运算符<<和运算符>>但它给了我运行时错误.
这是我的代码
#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;
}

输出

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

顺便说一下,我正在使用Visual Studio 2010但我已经尝试过使用Fedora 16并获得相同的结果!

@H_403_11@

解决方法

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

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

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

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;
}
@H_403_11@ @H_403_11@ 原文链接:https://www.f2er.com/c/117992.html

猜你在找的C&C++相关文章