streamstring缓冲流

目录

1、字符串流(字符串缓冲区)

2、istreamstring

2、ostringstream

3、stringstream


1、字符串流(字符串缓冲区)

相对于程序中变量而言的输入输出。

1)istringstream类用于执行C++风格的字符串流的输入操作;

2)ostringstream类用于执行C++风格的字符串流的输出操作;

3)strstream类同时可以支持C++风格的字符串流的输入输出操作。

2、istreamstring

#include <iostream>
#include <sstream>

using namespace std;

int main()
{
	//C++类型的字符串流的输入操作
    //将大字符串分割成小字符串
	istringstream is;
	is.str("1 abc");

	cout << is.str() << endl;

	int a = 0;
	char ch1, ch2, ch3;
	//根据变量的类型 从字符串流(字符串缓冲区)中取数据
	is >> a >> ch1 >> ch2 >> ch3;
	cout << a << ends 
		<< ch1 << ends 
		<< ch2 << ends 
		<< ch3 << endl;
	//缓冲区中的数据 读完后还存在
	cout << is.str() << endl;

	//不支持 动态的添加数据 <<
	//is << "defg";

	//会替换原数据
	is.str("2 d");
	cout << is.str() << endl;

	//清空状态 不是清空流数据
	is.clear();
	
	//测试 流再次输出数据的描述符位置,从头开始。
	int b = 0;
	char ch4;
	is >> b;
	is >> ch4;
	cout << b << ends << ch4 << endl;

	//读取空数据返回-1
	char ch5 = is.peek();	//查看下一个字符是什么,不会真正读走字符
	cout << ch5 << endl;

	//将字符ch4放回流中
	is.putback(ch4);
	is >> ch5;
	cout << ch5 << endl;

	//清空数据
	is.str("");
	cout << is.str() << endl;

	
	system("pause");
}

2、ostringstream

#include <iostream>
#include <sstream>

using namespace std;

int main()
{
	//C++风格的字符串输出流
	//将小字符串 合成大字符串
	ostringstream os1;
	ostringstream os2("1 abc");
	os1 << os2.str();	//可以动态添加数据
	cout << os1.str() << ends << os2.str() << endl;

	//注意,该操作会使 asd覆盖1 abc得到asdbc。 填充数据会从第一位开始一个一个覆盖
	os2 << "asd";
	cout << os2.str() << endl;

	//向字符流中添加字符
	os1.put('d');
	cout << os1.str() << endl;

	//重新填充字符流
	os1.str(" ");
	cout << os1.str() << endl;

	system("pause");
}

3、stringstream

#include <iostream>
#include <sstream>

using namespace std;

int main()
{

	//同时具备 C++风格的字符串流的输入输出操作
	stringstream ios;

	//添加数据
	ios << "1 abc";
	ios << " 2 def";

	int a, b;
	char ch1, ch2, ch3;
	a = b = 0;
	ch1 = ch2 = ch3 = ' ';
	string str;

	cout << ios.str() << endl;

	//读出数据
	ios >> a >> ch1 >> ch2 >> ch3 >> b >> str;
	cout << a << ends << ch1 << ends << ch2 << ends << ch3 << ends
		<< b << ends << str << endl;
	system("pause");

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值