stringstream的用法

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;
}

运行结果:
在这里插入图片描述

  • 4
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值