zoukankan      html  css  js  c++  java
  • 【转载】boost::lexical_cast 的使用

    1,字符串 到 数值类型的转换

    2,数值 到 字符串的转换
    3,异常处理情况
    4,boost::lexical_cast 的原型:
    template<typename Target, typename Source>
        Target lexical_cast(Source arg);
    lexical_cast 是依赖于字符串流 std::stringstream 的,其原理也是相当的简单:把源类型 (Source) 读入到字符流中,再写到目标类型 (Target) 中。但这里同时也带来了一些限制:
      - 输入数据 (arg) 必须能够 “完整” 地转换,否则就会抛出 bad_lexical_cast 异常。例如:
       int i = boost::lexical_cast<int>("123.456"); // this will throw
        因为 “123.456” 只能 “部分” 地转换为 123,不能 “完整” 地转换为 123.456,还是让我们需要适当的注意一些这两个模板参数就好了。
      - 由于 Visual C++ 6 的本地化(locale)部分实现有问题,如果使用了非默认的 locale,可能会莫名其妙地抛出异常。
      - 源类型 (Source) 必须是一个可以输出到输出流的类型(OutputStreamable),也意味着该类型需要 operator<< 被定义。
      - 同样的,目标类型 (Target) 必须是一个可以输入到输入流的类型 (InputStreamable),也意味着该类型需要 operator>> 被定义。
      - 另外,Both Source and Target are CopyConstructible。
      - Target is DefaultConstructible。
    其中,下面的四个限制是在使用自定义类型之间转换时必须做的一些工作的(当然流行的使用的 C 库函数等等都是不可以处理自定义类型之间的转换的)。

    #include <boost/lexical_cast.hpp>
    #include <iostream>
    #include <string> 
    #define ERROR_LEXICAL_CAST     1 
    int main()
    {
        using boost::lexical_cast;
        int         a = 0;
        double        b = 0.0;
        std::string s = ""; 
        int            e = 0;    
        try
        { 
            // ----- 字符串 --> 数值 
            a = lexical_cast<int>("123");
            b = lexical_cast<double>("123.12");
            // ----- 数值 --> 字符串
            s = lexical_cast<std::string>("123456.7"); 
            // ----- 异常处理演示
            e = lexical_cast<int>("abc");
        }
        catch(boost::bad_lexical_cast& e)
        {
            // bad lexical cast: source type value could not be interpreted as target
            std::cout << e.what() << std::endl;
            return ERROR_LEXICAL_CAST;
        } 
        
        std::cout << a << std::endl;    // 输出:123 
        std::cout << b << std::endl;    // 输出:123.12 
        std::cout << s << std::endl;     // 输出:123456.7 
        return 0;
    }
  • 相关阅读:
    关于Maven项目的pom.xml中的依赖或插件失效的解决方法
    java引用数据类型在方法中的值传递
    java匹配http或https的url的正则表达式20180912
    java正则表达式的进阶使用20180912
    java线程池 多线程 搜索包含关键字的文件路径
    魔术球问题
    [SDOI2009]晨跑
    [洛谷P2045]方格取数加强版
    最小路径覆盖问题
    最长不下降子序列问题
  • 原文地址:https://www.cnblogs.com/lzjsky/p/2035008.html
Copyright © 2011-2022 走看看