zoukankan      html  css  js  c++  java
  • 用boost::lexical_cast进行数值转换

    在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");
        }

     

  • 相关阅读:
    Golang error 的突围
    深度解密Go语言之 scheduler
    深度解密Go语言之channel
    如何打造一份优雅的简历?
    Go 程序是怎样跑起来的
    曹大谈内存重排
    从零开始使用 Webpack 搭建 Vue 开发环境
    纯样式无脚本无图片自定义单/复选框
    从零开始使用 Webpack 搭建 Vue3 开发环境
    JS遍历对象的几种方法
  • 原文地址:https://www.cnblogs.com/TianFang/p/2892506.html
Copyright © 2011-2022 走看看