1 C++利用sstream进行数据类型转换
#include <iostream>
#include <sstream>
using namespace std;
template <class T, class K>
K convert(T tmp){
stringstream ss;
K k;
ss << tmp;
ss >> k;
return k;
}
int main(){
string s;
s = convert<int, string>(45);
cout << s;
return 0;
}
/home/hejinyang/.CLion2016.2/system/cmake/generated/mypro01-f76d0ccf/f76d0ccf/Debug/mypro01
8855
Process finished with exit code 0
2 c++11以后可用自带的函数进行字符串与其它数据类型的转换
2.1 其它类型转为字符串(声明在std中)
函数 | 功能 |
---|
string to_string (int val) | int --> string |
string to_string (long val) | long --> string |
string to_string (long long val) | long long --> string |
string to_string (unsigned val) | unsigned --> string |
string to_string (unsigned long val) | unsigned long --> string |
string to_string (unsigned long long val) | unsigned long long --> string |
string to_string (float val) | float --> string |
string to_string (double val) | double --> string |
string to_string (long double val) | long double --> string |
2.2 字符串转其它类型
int stoi (const string& str, size_t* idx = 0, int base = 10);
int stoi (const wstring& str, size_t* idx = 0, int base = 10);
double stod (const string& str, size_t* idx = 0);
double stod (const wstring& str, size_t* idx = 0);
float stof (const string& str, size_t* idx = 0);
float stof (const wstring& str, size_t* idx = 0);
long stol (const string& str, size_t* idx = 0, int base = 10);
long stol (const wstring& str, size_t* idx = 0, int base = 10);
long double stold (const string& str, size_t* idx = 0);
long double stold (const wstring& str, size_t* idx = 0);
long long stoll (const string& str, size_t* idx = 0, int base = 10);
long long stoll (const wstring& str, size_t* idx = 0, int base = 10);
unsigned long stoul (const string& str, size_t* idx = 0, int base = 10);
unsigned long stoul (const wstring& str, size_t* idx = 0, int base = 10);
unsigned long long stoull (const string& str, size_t* idx = 0, int base = 10);
unsigned long long stoull (const wstring& str, size_t* idx = 0, int base = 10);