boost中的数据类型转换之lexical_cast

概述

C++程序中数据类型转换是十分常用的操作,本文介绍如何使用boost库来实现数据类型的转换。

lexical_cast

boost中通过boost::lexical_cast一系列模板函数来实现数据类型转换,boost::lexical_cast的头文件为

#include <boost/lexical_cast.hpp>

基本原型定义如下:

namespace boost 
{
    template <typename Target, typename Source>
    inline Target lexical_cast(const Source &arg)
    {
        Target result;

        if (!boost::conversion::detail::try_lexical_convert(arg, result)) {
            boost::conversion::detail::throw_bad_cast<Source, Target>();
        }

        return result;
    }
}

基本使用方法

#include<boost/lexical_cast.hpp>
#include <iostream>
int main(int argc,const char* argv[])
{
    //字符串转为数值
    int n = boost::lexical_cast<int>("520");
    std::cout << n <<std::endl;

    //字符串转为float
    float f = boost::lexical_cast<float>("123.456");
    std::cout << f <<std::endl;

    //字符串转为double
    double d = boost::lexical_cast<double>("3.14159");
    std::cout << d << std::endl;

    //取前3位字符转换为double
    double d1 = boost::lexical_cast<double>("3.14159",3);
    std::cout << d1 << std::endl;

    //double转为string
    std::string s = boost::lexical_cast<std::string>(1.121415926);
    std::cout << s <<std::endl;

    //16进制数转为string
    std::string shex = boost::lexical_cast<std::string>(0x000a);
    std::cout << shex << std::endl;

    return 0;
}

上面的程序运行结果如下:

[root@sansec fcztest]# ./a.out
520
123.456
3.14159
3.1
1.1214159260000001
10

异常处理

当使用lexical_cast进行数据类型转换时,如果转换错误会抛出异常,因此标准的写法应该再转换中通过try-catch块进行异常处理,如下

#include<boost/lexical_cast.hpp>
#include <iostream>
int main(int argc,const char* argv[])
{
    //字符串转为float
    float f = 0.0f;
    try
    {
        f = boost::lexical_cast<float>("123.456f");
    }
    catch(const boost::bad_lexical_cast & e)
    {
        std::cerr << e.what() << '\n';
    }
    std::cout << f <<std::endl;
    return 0;
}

运行结果如下:

[root@sansec fcztest]# ./a.out
bad lexical cast: source type value could not be interpreted as target
f=0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

君子不器(FCZ)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值