c++整型与字符串的互转方式

  

<强> flyfish

  

<强>字符串转整型

  

C的方法装运箱是char *或者const char *类型的字符串
  

  

int num=atoi (str);
  int num=strtol(装运箱,NULL, 10);

  

//10表示进制

  

<强> C + + 11的方法

        空白test1 ()   {   std:: string str1=?”;      std:: string str2=" 1.5 ";      std:: string str3=?用文字”;            int myint1=std:: stoi (str1);      int myint2=std:: stoi (str2);      int myint3=std:: stoi (str3);         std:: cout & lt; & lt;“std:: stoi (\“& lt; & lt;str1 & lt; & lt;“\”)是“& lt; & lt;myint1 & lt; & lt;' \ n ';      std:: cout & lt; & lt;“std:: stoi (\“& lt; & lt;str2 & lt; & lt;“\”)是“& lt; & lt;myint2 & lt; & lt;' \ n ';      std:: cout & lt; & lt;“std:: stoi (\“& lt; & lt;str3 & lt; & lt;“\”)是“& lt; & lt;myint3 & lt; & lt;' \ n ';   }      

结果输出

        std:: stoi(“1”)是1   std:: stoi(" 1.5 ")是1   std:: stoi(用文字“1”)是1         

//源码参考cplusplus.com

        空白test2 ()   {      std:: string str_dec=?001太空漫游”;   std:: string str_hex=40 c3”;   std:: string str_bin=?10010110001”;   std:: string str_auto=" 0 x7f ";      std:: string: size_type深圳;//size_t的别名      int i_dec=std:: stoi (str_dec,和深圳);   int i_hex=std:: stoi (str_hex nullptr 16);   int i_bin=std:: stoi (str_bin nullptr 2);   int i_auto=std:: stoi (str_auto nullptr 0);      std:: cout & lt; & lt;str_dec & lt; & lt;”:“& lt; & lt;i_dec & lt; & lt;”和“& lt; & lt;str_dec.substr(深圳)& lt; & lt;“\ n”;   std:: cout & lt; & lt;str_hex & lt; & lt;”:“& lt; & lt;i_hex & lt; & lt;' \ n ';   std:: cout & lt; & lt;str_bin & lt; & lt;”:“& lt; & lt;i_bin & lt; & lt;' \ n ';   std:: cout & lt; & lt;str_auto & lt; & lt;”:“& lt; & lt;i_auto & lt; & lt;' \ n ';      返回0;   }            

输出         2001太空漫游:2001和[太空漫游)   40 c3: 16579   -10010110001:-1201   0 x7f: 127         

其他类型类似

  

无符号整型

  

stoul   

浮点型   

stof   

数值转字符串

  

std:: string s;
  s=std:: to_string (1) +“int”;

  

其他数值类型类似

  

s=std:: to_string(3.14度)+“浮动。”;
  

  

以上这篇c++整型与字符串的互转方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

c++整型与字符串的互转方式