【C++】C++中int與string的相互轉換


一、int轉string

1.c++11標准增加了全局函數std::to_string:

string to_string (int val);

string to_string (long val);

string to_string (long long val);

string to_string (unsigned val);

string to_string (unsigned long val);

string to_string (unsigned long long val);

string to_string (float val);

string to_string (double val);

string to_string (long double val);

Example:

// 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;
}

 

Output:
pi is 3.141593
28 is a perfect number
2.采用sstream中定義的字符串流對象來實現
ostringstream os; //構造一個輸出字符串流,流內容為空
int i = 12;
os << i; //向輸出字符串流中輸出int整數i的內容
cout << os.str() << endl; //利用字符串流的str函數獲取流中的內容

二、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
以上一句,需要特別說明,這個sz變量,是為了獲取在轉換過程中,轉換了多少位的數據。如果不需要這個數據,可以設置為0
所以這個變量,也可以直接定義為 site_z sz; 不一定按上面的定義方法

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; }

 

Output:
2001, A Space Odyssey: 2001 and [, A Space Odyssey]
40c3: 16579
-10010110001: -1201
0x7f: 127
2.采用標准庫中atoi函數,對於其他類型也都有相應的標准庫函數,比如浮點型atof(),long型atol()等等
string s = "12";
int a = atoi(s.c_str());
3.采用sstream頭文件中定義的字符串流對象來實現轉換
istringstream is("12"); //構造輸入字符串流,流的內容初始化為“12”的字符串
int i;
is >> i; //從is流中讀入一個int整數存入i中

參考資料:
http://blog.csdn.net/chavo0/article/details/51038397

http://blog.csdn.net/na_beginning/article/details/53576123
---------------------
作者:HarryLi
來源:CSDN
原文:https://blog.csdn.net/u010510020/article/details/73799996
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM