zoukankan      html  css  js  c++  java
  • C++ int 和 string 转换

     int转化为string

    1、使用itoa(int to string)

    //char *itoa( int value, char *string,int radix);
    // 原型说明:
    // value:欲转换的数据。
    // string:目标字符串的地址。
    // radix:转换后的进制数,可以是10进制、16进制等。
    // 返回指向string这个字符串的指针
    
    int aa = 30;
    char c[8];
    itoa (aa,c,16);
    cout << c << endl; // 1e
    

      

    注意:itoa并不是一个标准的C函数,它是Windows特有的,如果要写跨平台的程序,请用sprintf。

    2、使用sprintf

    // int sprintf( char *buffer, const char *format, [ argument] … );
    //参数列表
    // buffer:char型指针,指向将要写入的字符串的缓冲区。
    // format:格式化字符串。
    // [argument]...:可选参数,可以是任何类型的数据。
    // 返回值:字符串长度(strlen)
    
    int aa = 30;
    char c[8]; 
    int length = sprintf(c, "%05X", aa); 
    cout << c << endl; // 0001E

    3、使用stringstream

    int aa = 30;
    stringstream ss;
    ss << aa; 
    string s1 = ss.str();
    cout << s1 << endl; // 30
    
    string s2;
    ss >> s2;
    cout << s2 << endl; // 30

    可以这样理解,stringstream可以吞下不同的类型,根据s2的类型,然后吐出不同的类型。
    4、使用boost库中的lexical_cast

    int aa = 30;
    string s = boost::lexical_cast<string>(aa);
    cout << s << endl; // 30

    3和4只能转化为10进制的字符串,不能转化为其它进制的字符串。

    5、to_string()

    int a;
    string s;
    s += to_string(a);
    

      


     string转化为int

    1、使用strtol(string to long) 

    string s = "17";
    char* end;
    int i = static_cast<int>(strtol(s.c_str(),&end,16));
    cout << i << endl; // 23
    
    i = static_cast<int>(strtol(s.c_str(),&end,10));
    cout << i << endl; // 17

    2、使用sscanf

    int i;
    sscanf("17","%D",&i);
    cout << i << endl; // 17
    
    sscanf("17","%X",&i);
    cout << i << endl; // 23
    
    sscanf("0X17","%X",&i);
    cout << i << endl; // 23

    3、使用stringstream

    string s = "17";
    stringstream ss;
    ss << s;
    
    int i;
    ss >> i;
    cout << i << endl; // 17

    注:stringstream可以吞下任何类型,根据实际需要吐出不同的类型。
    4、使用boost库中的lexical_cast

    string s = "17";
    int i = boost::lexical_cast<int>(s);
    cout << i << endl; // 17
  • 相关阅读:
    nginx proxy_cache 缓存配置[转]
    MongoDB使用小结:一些常用操作分享
    PHP读取Mongodb数据报错,Cannot natively represent the long 8331412483000 on this platform
    MongoDB 学习笔记(python操作)
    Python 中 os.path模板
    Python 优雅的操作字典【转】
    MongoDB 一对多关系建模
    nginx之location配置
    MongoDB安装Windows服务
    .net4.0 请求HTTPS出错:未能创建 SSL/TLS 安全通道
  • 原文地址:https://www.cnblogs.com/yellowzunzhi/p/11075142.html
Copyright © 2011-2022 走看看