代码改变世界

[boost] boost::lexical_cast类型转换

2013-04-17 21:57  鉴于  阅读(451)  评论(0编辑  收藏  举报

boost是一个开源的c++开发库,提供了一些通用库用来弥补c++标准库的不足。

boost::lexical_cast是一个类型转换库,可用于不同类型之间的转换,字符串、整型数等。

具体使用例子如下:

#include <iostream>
#include <boost/lexical_cast.hpp>

int main(int argc, char* argv[])
{
    std::string strNum = "1.0";
    float num = boost::lexical_cast<float>(strNum);      // 从std:::string 转成浮点数

    strNum = "2.49484984abd";
    try
    {
        num = boost::lexical_cast<float>(strNum);         // 如果该字符串不是一个浮点数,则会报异常,需要用try-catch捕获
    }
    catch(boost::bad_lexical_cast&  ex)
    {
        std::cout << "Failed to change type." << std::endl;
    }

    num = 2.484;
    std::string  s2  = boost::lexical_cast<std::string>(num);

    std::wstring  w2  =  L"2.498494894";                       // 双字节字符串转成浮点数
    float wNum = boost::lexical_cast<float>(w2);
    return 0;
}