std::to_string
C++ Strings library std::basic_string
Defined in header

(1) std::string to_string( int value );
(2) std::string to_string( long value );
(3) std::string to_string( long long value );
(4) std::string to_string( unsigned value );
(5) std::string to_string( unsigned long value );
(6) std::string to_string( unsigned long long value );
(7) std::string to_string( float value );
(8) std::string to_string( double value );
(9) std::string to_string( long double value );
#include <iostream>
#include <string>

int main()
{
    double f = 23.43;
    std::string f_str = std::to_string(f);
    std::cout << f_str << '\n';
}
输出:

23.430000
// to_string example  
#include <iostream>   // std::cout  
#include <string>     // std::string, std::to_string  

int main ()  
{  
  std::string pi = "pi is " + std::to_string(3.1415926);  
  std::string perfect = std::to_string(1+2+4+7+14) + " is a perfect number";  
  std::cout << pi << '\n';  
  std::cout << perfect << '\n';  
  return 0;  
}
pi is 3.141593  
28 is a perfect number

二、string转int
1.可以使用std::stoi/stol/stoll等等函数
Example:

// stoi example  
#include <iostream>   // std::cout  
#include <string>     // std::string, std::stoi  

int main ()  
{  
  std::string str_dec = "2001, A Space Odyssey";  
  std::string str_hex = "40c3";  
  std::string str_bin = "-10010110001";  
  std::string str_auto = "0x7f";  

  std::string::size_type sz;   // alias of size_t  

  int i_dec = std::stoi (str_dec,&sz);  
  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 << str_dec << ": " << i_dec << " and [" << str_dec.substr(sz) << "]\n";  
  std::cout << str_hex << ": " << i_hex << '\n';  
  std::cout << str_bin << ": " << i_bin << '\n';  
  std::cout << str_auto << ": " << i_auto << '\n';  

  return 0;  
}
2001, A Space Odyssey: 2001 and [, A Space Odyssey]  
40c3:  16579  
-10010110001: -1201  
0x7f: 127
string s = "12";   
int a = atoi(s.c_str());

首先atoi和strtol都是c里面的函数,他们都可以将字符串转为int,它们的参数都是const char*,因此在用string时,必须调c_str()方法将其转为char*的字符串。或者atof,strtod将字符串转为double,它们都从字符串开始寻找数字或者正负号或者小数点,然后遇到非法字符终止,不会报异常:

int main() {
    using namespace std;
    string strnum=" 232s3112";
    int num1=atoi(strnum.c_str());
    long int num2=strtol(strnum.c_str(),nullptr,10);
    cout<<"atoi的结果为:"<<num1<<endl;
    cout<<"strtol的结果为:"<<num2<<endl;
    return 0;
}
atoi的结果为:232
strtol的结果为:232

可以看到,程序在最开始遇到空格跳过,然后遇到了字符’s’终止,最后返回了232。

这里要补充的是strtol的第三个参数base的含义是当前字符串中的数字是什么进制,而atoi则只能识别十进制的。例如:

using namespace std;
    string strnum="0XDEADbeE";
    int num1=atoi(strnum.c_str());
    long int num2=strtol(strnum.c_str(),nullptr,16);
    cout<<"atoi的结果为:"<<num1<<endl;
    cout<<"strtol的结果为:"<<num2<<endl;
    return 0;
atoi的结果为:0
strtol的结果为:233495534