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; 
        }
        
    }
    
  • 相关阅读:
    jquery、js调用iframe父窗口与子窗口元素的方法整理
    js中的各种宽高以及位置总结
    javascript call与apply关键字的作用
    javascript之window对象
    CSS3 3D立方体效果
    CSS3 3D transform变换
    JS查找字符串中出现次数最多的字符
    写一个函数将传入的字符串转换成驼峰表示法
    数组去重方法
    内核升级得一个模范
  • 原文地址:https://www.cnblogs.com/logchen/p/10217324.html
Copyright © 2011-2022 走看看