用stringstream类,口诀:过滤一下就转化
头文件#include<sstream>
例子:将整数12和浮点数12.34转化为字符串
int main()
{
int x = 12;
double d = 12.34;
string s;
//创建一下对象str
stringstream str;
//过滤一下就转化
str << x;
str >> s;
for (int i = 0; i < s.size(); i++)
{
cout << s[i] << " ";
}
cout << endl;
//清空一下str
str.clear();
//过滤一下就转化
str << d;
str >> s;
for (int i = 0; i < s.size(); i++)
{
cout << s[i] << " ";
}
cout << endl;
return 0;
}
结果
将字符串转换为整数(浮点数)
例子:将字符串“12”和“12.34”转换为整型和浮点型
int main()
{
int x = 0;
double d = 0;
string s1 = "12";
string s2 = "12.34";
//创建一下对象str
stringstream str;
//过滤一下就转化
str << s1;
str >> x;
cout << x << endl;
//清空一下str
str.clear();
//过滤一下就转化
str << s2;
str >> d;
cout << d << endl;
return 0;
}
结果