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