zoukankan      html  css  js  c++  java
  • [转] boost:lexical_cast用法

    转载地址:http://www.habadog.com/2011/05/07/boost-lexical_cast-intro/

    一、lexical_cast的作用
    lexical_cast使用统一的接口实现字符串与目标类型之间的转换。

    二、lexical_cast与c/c++提供类似接口的比较
    标准c家族中包含此类函数,例如atoi与itoa等,它们的缺点是:
    (1)各个转换都是单向的,双向转换为不同函数,各种转换函数不同,接口众多;
    (2)仅支持基础数据类型的子集,如int,long,double;
    (3)不能提供统一的接口,易用性差;

    c++中提供了stringstream,使用它进行格式转换可读性较差,使用起点较高,只是简单的转换,stringstream太重量级。

    boost提供了lexical_cast,使用统一接口形式实现任意类型之间的转换,增强了易用性。但如果需要严密控制精度的转换,仍然推荐使用stringstream;数值之间的转换,推荐使用numeric_cast。

    三、lexical_cast的接口形式

    1
    2
    3
    template<typename target,="" typename="" source="">
    Target lexical_cast(const Source& arg);
    </typename>

    四、lexical_cast的样例代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    #include "iostream"
    #include "boost/lexical_cast.hpp" // 需要包含的头文件
     
    using boost::lexical_cast;
    using boost::bad_lexical_cast;
    using namespace std;
     
    int main()
    {
        char* p="32768";
        int i=0;
        try
        {
            i=lexical_cast<int>(p); // 将字符串转化为整数
        }
        catch(bad_lexical_cast&)    // 转换失败会抛出一个异常
        {
            i=0;
        }
        cout << i << endl;
        return i;
    }
    </int>
  • 相关阅读:
    HDU 1009 FatMouse' Trade
    python正则表达式
    Python学习week5
    Python学习week4
    Python学习week3
    Python学习week2
    Python学习week1
    生活的艰辛(最小割,最大密度子图)
    最大获利(最小割,最大权闭合图,最大密度子图)
    最大密度子图
  • 原文地址:https://www.cnblogs.com/457220157-FTD/p/4835981.html
Copyright © 2011-2022 走看看