1.用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.字符串拼接,代码如下:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
#include<sstream>
int main()
{
stringstream sstream;
sstream << "first" << " " << "second";
sstream << " third times";
cout << "输出字符串: " << sstream.str() << endl;
sstream.str("");
sstream << "one more time";
cout << "清空字符串后,输出为: " << sstream.str() << endl;
return 0;
}
运行结果:
3.将数值类型数据格式化为字符串,代码如下:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
#include<sstream>
int main()
{
int a = 865;
string sa;
stringstream s;
s << a;
s >> sa;
string strValue1;
strValue1 = s.str();
cout << strValue1 << endl;
s.str("");
s.clear();
double d = 12.34;
s << d;
s >> sa;
string strValue2;
strValue2 = s.str();
cout << strValue2 << endl;
return 0;
}
运行结果:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)