1.用stringstream来分割指定的字符字符串,代码如下:
//用stringstream来分割指定的字符字符串
#include <iostream>
#include <sstream>
#include <vector>
#include<queue>
#include<string>
using namespace std;
int main() {
string str = "1,2,3,4,5";
stringstream ss(str);
string item;
queue<string> q;
cout << str << endl;
while(getline(ss, item, ','))
cout << item << ' ';
return 0;
}
运行结果:
2.字符串拼接,代码如下:
//stringstream用于字符串的拼接
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
#include<sstream>
int main()
{
stringstream sstream;
// 将多个字符串放入 sstream 中
sstream << "first" << " " << "second";
sstream << " third times";
cout << "输出字符串: " << sstream.str() << endl;
// 清空 sstream
sstream.str("");
sstream << "one more time";
cout << "清空字符串后,输出为: " << sstream.str() << endl;
return 0;
}
运行结果:
3.将数值类型数据格式化为字符串,代码如下:
//stringstream将数值类型数据格式化为字符串
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
#include<sstream>
int main()
{
int a = 865;
string sa;
// 将一个整形变量转化为字符串,存储到string类对象中
stringstream s;
s << a;
s >> sa;
string strValue1;
strValue1 = s.str();
cout << strValue1 << endl;
// 将stringstream底层管理string对象设置成"", 否则多次转换时,会将结果全部累积在底层string对象中
s.str("");
s.clear();// 清空s, 不清空会转化失败
double d = 12.34;
s << d;
s >> sa;
string strValue2;
//这个方法会把管理的整个string对象返回,不会受读/写指针的影响
strValue2 = s.str();// str()方法:返回stringsteam中管理的string类型
cout << strValue2 << endl;
return 0;
}
运行结果: