用boost::lexical_cast用法解析

包含头文件

#include <boost/lexical_cast.hpp>

using namespace boost;


1.lexical_cast库进行“字面量”转换,类似于C语言中的atoi函数,可以进行字符串、整数/浮点数之间的转换。

使用lexical_cast时要注意,要转换成数字的字符串只能有数字和小数点,不能出现字母(表示指数的e/E除外)或其他非数字字符,也就是说,lexical_cast不能转换如“123L”、“0x100”这样c++语法许可的数字字面量字符串。

2.当lexical_cast无法执行转换操作时会抛出异常bad_lexical_cast,因此我们需要用try/catch保护转换

举例子如下:

在STL库中,我们可以通过stringstream来实现字符串和数字间的转换:



    int i = 0;
    stringstream ss;


    ss << "123";
    ss >> i;


但stringstream是没有错误检查的功能,例如对如如下代码,会将i给赋值为12.


    ss << "12.3";
    ss >> i;


甚至连这样的代码都能正常运行:


    ss << "hello world";
    ss >> i;


这显然不是我们所想要看到的。为了解决这一问题,可以通过boost::lexical_cast来实现数值转换:


    int i = boost::lexical_cast<int>("123");
    double d = boost::lexical_cast<double>("12.3");


对于非法的转换,则会抛异常:


    try
    {
        int i = boost::lexical_cast<int>("12.3");
    }
    catch (boost::bad_lexical_cast& e)
    {
        cout << e.what() << endl;
    }


对于16机制数字的转换,可以以如下方式进行:


    template <typename ElemT>
    struct HexTo {
        ElemT value;
        operator ElemT() const {return value;}
        friend std::istream& operator>>(std::istream& in, HexTo& out) {
            in >> std::hex >> out.value;
            return in;
        }
    };


    int main(void) 
    {
        int x = boost::lexical_cast<HexTo<int>>("0x10"); 

    }


3.应用于自己的类

如果需要将lexical_cast应用于自己的类,把类转换成可理解的字符串(类似于java中的Object.toString),那么需要实现流输出操作符<<

demo如下:

#include <iostream>
using namespace std;


class DemoClass
{
public:
DemoClass();
~DemoClass();


friend std::ostream& operator <<(std::ostream& os, const DemoClass& x)
{
os << "DemoClass's Name";
return os;
}
};


int main(int argc, char *argv[])
{

cout << lexical_cast<string>(DemoClass()) << endl;
return 0;
}

输出结果:DemoClass's Name。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值