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
  • 相关阅读:
    带有“全选”的combotree
    combotree(组合树)的使用
    根据权限显示accordion
    accordion(折叠面板)的使用
    js中substr、substring、indexOf、lastIndexOf的用法
    EasyUI中使用自定义的icon图标
    EasyUI tree的三种选中状态
    C# List集合去重使用lambda表达式
    C# DataTable去重,根据列名去重保留其他列
    win10下部署.Net Web项目到IIS10
  • 原文地址:https://www.cnblogs.com/yellowzunzhi/p/11075142.html
Copyright © 2011-2022 走看看