zoukankan      html  css  js  c++  java
  • Boost--lexical_cast 一个方便安全高效的string转换库

    #include "boostlexical_cast.hpp"
    #include <vector>
    #include <iostream>
    #include <array>
    
    using namespace std;
    using boost::lexical_cast;
    using boost::bad_lexical_cast;
    
    int main()
    {
    
    // C++自带的函数不好记,且命名不统一,有些a开头有些是str开头
    /*  string转成其他类型
    atof     Convert string to double (function )
    atoi     Convert string to integer (function )
    atol     Convert string to long integer (function )
    atoll    Convert string to long long integer (function )
    strtod   Convert string to double (function )
    strtof   Convert string to float (function )
    strtol   Convert string to long integer (function )
    strtold  Convert string to long double (function )
    strtoll  Convert string to long long integer (function )
    strtoul  Convert string to unsigned long integer (function )
    strtoull Convert string to unsigned long long integer (function )
    sscanf()
       
       其他类型转string需要完全不同的方法
    stringstream strm;
    strm << int_val;
    string s = strm.str();
    sprintf()
    itoa  // non-standard
    */
    
    
        try
        {
            int s = 345;
    // 只需要使用同一个函数就可以完成不同类型的转换
            string str = lexical_cast<string>(s);
            str = "Message: " + lexical_cast<string>('A') + "==" + lexical_cast<string>(34.5);
            cout << str << endl;
    //也可以转成char类型的array
            array<char, 64> msg = lexical_cast< array<char, 64> >(23456);
    
            s = lexical_cast<int>("5678");
            //s = lexical_cast<int>("56.78"); // bad_lexical_cast
            //s = lexical_cast<int>("3456yut");  // bad_lexical_cast 
            s = lexical_cast<int>("3456yut", 4);  //ok
            cout << s << endl;
        }
        catch(bad_lexical_cast & e)
        {
            cout << "Exception caught:" << e.what() << endl; 
        }
        
    }
    
  • 相关阅读:
    【Golang】golang文本处理
    【Golang】golang中临时对象池sync.Pool
    WebSocket介绍
    【Linux】linux常用命令操作整理
    【PHP】php7新特性及其优化原理
    【Mysql】MySQL集群方案之PXC(percona xtradb cluster)
    【Linux】线上服务器要关注哪些参数
    service自动发现,yaml文件管理内外部端口访问
    service代理模式及负载均衡
    SET NLS_LANG=AMERICAN_AMERICA.AL32UTF8
  • 原文地址:https://www.cnblogs.com/logchen/p/10217324.html
Copyright © 2011-2022 走看看