std::to_string
C++ Strings library std::basic_string
Defined in header
() std::string to_string( int value );
() std::string to_string( long value );
() std::string to_string( long long value );
() std::string to_string( unsigned value );
() std::string to_string( unsigned long value );
() std::string to_string( unsigned long long value );
() std::string to_string( float value );
() std::string to_string( double value );
() std::string to_string( long double value );
#include <iostream>
#include <string>
int main()
{
double f = ;
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();
std::string perfect = std::to_string(++++) + " is a perfect number";
std::cout << pi << '\n';
std::cout << perfect << '\n';
return ;
}
pi is
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,);
int i_bin = std::stoi (str_bin,nullptr,);
int i_auto = std::stoi (str_auto,nullptr,);
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 ;
}
, A Space Odyssey: and [, A Space Odyssey]
c3:
-10010110001: -
x7f:
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,);
cout<<"atoi的结果为:"<<num1<<endl;
cout<<"strtol的结果为:"<<num2<<endl;
return ;
}
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,);
cout<<"atoi的结果为:"<<num1<<endl;
cout<<"strtol的结果为:"<<num2<<endl;
return ;
atoi的结果为:0
strtol的结果为:233495534