stringstream流输入输出(C++引入的概念)

1、之前刷leetcode发现这个函数对于对单词的计数很好用,总是忘记怎么用,自己总结记录一下。

2、头文件  #include <sstream>

3、<sstream> 定义了三个类:istringstream、ostringstream 和 stringstream,分别用来进行流的输入、输出和输入输出操作,也就是in out 。

5、流输出举例

#include <iostream>
#include <sstream>
using namespace std;

int main()
{
	string str;
	str = "hello i am lv";
	stringstream ss(str);
	//我如果要计算长度的话
	int count = 0;
	while (ss >> str)//这里用了流输出
	{
		count++;
	}
	cout << count << endl;//这里会输出4
	ss.str("");//字符串清空
	
	return 0;
}

在这里面我可以使用字符串初始化流输入输出类型。

6、流输入举例

#include <iostream>
#include <sstream>
#include <algorithm>
using namespace std;

int main()
{
	string str;
	str = "hello i am lv";
	stringstream ss;
	ss << str;
	str = "hello i am bin";
	ss << str;
	//cout << ss << endl;//这里我们不能直接输出流类型的要用str()转换成string类型才能输出
	cout << ss.str() << endl;//这里就会输出hello i am lvhello i am bin
	return 0;
}

7、多次转换需要使用clear()清除

#include <iostream>
#include <sstream>
#include <algorithm>
using namespace std;

int main()
{
	string str;
	str = "147222";
	stringstream ss;
	ss << str;
	//cout << ss << endl;//这里我们不能直接输出流类型的要用str()转换成string类型才能输出
	cout << ss.str() << endl;//这里就会输出hello i am lvhello i am bin
	ss.clear();
	int i;
	ss >> i;
	cout << i << endl;
	return 0;
}

总结:stringstream这个类型对于单词来说很好用。

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值