c/c++各种数据类型转换
1.字符转数字
char a = 'd'; char b = 'm'; int m; m = a + b - '0'; cout << "m=" << m << endl;
2.数字转字符串
#include<iostream> #include<cstring> #include<cstdlib> #include<sstream> using namespace std; int main() { stringstream ss; string s; int a = 12345; ss << a; ss >> s; }
3.字符串转数字
#include<iostream> #include<cstring> #include<cstdlib> #include<sstream> using namespace std; int main() { stringstream ss; string s = “12345”; int a ; ss << s; ss >> a; }
4.字符转字符串
#include<iostream> using namespace std; int main() { char ch = 'a'; char s[2] = {ch, 0}; string s1 = s; }
重推stringstream类
out_type change(in_type t) { stringstream ss; ss << t; //向流中传值 out_type result; //存储转化结果 ss >> result; //将结果写入result return result; return result; }