原創文章,轉載請註明: 轉載自勤奮的小青蛙
本文鏈接地址: 【整理】C++ string轉int,string轉double,string轉long,int轉string,double轉string…
C++開發中,經常遇到各種基本類型與string的轉換,掌握本博文,便可以輕鬆應對C++各基本類型與string的轉換(比如:
int轉string,double轉string,long轉string,string轉int,string轉double,string轉long
…)。
第一種:基於C++ 11標準:
基於C++11標準
如果你用的編譯器是基於最新的C++11標準,那麼這個問題就變的很簡單,因爲中已經封裝好了對應的轉換方法:
標準庫中定義了to_string(val);可以將其它類型轉換爲string。還定義了一組stoi(s,p,b)、stol(s,p,b)、stod(s,p,b)等轉換函數,可以函數,可以分別轉化成int、long、double等.
stoi(s,p,b);stol(s,p,b);stoul(s,p,b);stoll(s,p,b);stoull(s,p,b); 返回s的起始子串(表示整數內容的字符串)的數值,返回值的類型分別爲:int、long、unsigned long、long long、unsigned long long.其中b表示轉換所用的基數,默認爲10(表示十進制).p是size_t的指針,用來保存s中第一個非數值字符的下標,p默認爲0,即函數不返 回下標.
stof(s, p); stod(s, p); stold(s, p); 返回s的起始子串(表示浮點數內容)的數值,返回值的類型分別是float、double、long double.參數p的作用與整數轉換函數中的一樣。
voidtestTypeConvert()
{
//int --> string
inti = 5;
string s = to_string(i);
cout << s << endl;
//double --> string
doubled = 3.14;
cout << to_string(d) << endl;
//long --> string
longl = 123234567;
cout << to_string(l) << endl;
//char --> string
charc = 'a';
cout << to_string(c) << endl; //自動轉換成int類型的參數
//char --> string
string cStr; cStr += c;
cout << cStr << endl;
s = "123.257";
//string --> int;
cout << stoi(s) << endl;
//string --> int
cout << stol(s) << endl;
//string --> float
cout << stof(s) << endl;
//string --> doubel
cout << stod(s) << endl;
}
第一種方法記得編譯的時候加上支持C++ 11的參數:-std=c++0x
輸出結果:
5
3.140000
123234567
97
a
123
123
123.257
123.257
第二種:C++ 11標準之前:
C++11標準之前
C++11標準之前沒有提供相應的方法可以調用,就得自己寫轉換方法了,代碼如下:
從其它類型轉換爲string,定義一個模板類的方法。
從string轉換爲其它類型,定義多個重載函數。
#include <strstream>
template<classT>
string convertToString(constT val)
{
string s;
std::strstream ss;
ss << val;
ss >> s;
returns;
}
intconvertStringToInt(conststring &s)
{
intval;
std::strstream ss;
ss << s;
ss >> val;
returnval;
}
doubleconvertStringToDouble(conststring &s)
{
doubleval;
std::strstream ss;
ss << s;
ss >> val;
returnval;
}
longconvertStringToLong(conststring &s)
{
longval;
std::strstream ss;
ss << s;
ss >> val;
returnval;
}
voidtestConvert()
{
//convert other type to string
cout << "convert other type to string:" << endl;
string s = convertToString(44.5);
cout << s << endl;
intii = 125;
cout << convertToString(ii) << endl;
doubledd = 3.1415926;
cout << convertToString(dd) << endl;
//convert from string to other type
cout << "convert from string to other type:" << endl;
inti = convertStringToInt("12.5");
cout << i << endl;
doubled = convertStringToDouble("12.5");
cout << d << endl;
longl = convertStringToLong("1234567");
cout << l << endl;
}
結果如下:
convert other type to string:
44.5
125
3.14159
convert from string to other type:
12
12.5
1234567