string 流(sstream头文件下属的三个类型)

sstream头文件定义了三个类型来支持内存IO,这些类型可以向string写入数据,也可以从string流中读取数据。

istringstream 从string 读取数据, ostreamstream向string写入数据, 而头文件stringstream既可从string读取数据也可向string写入数据。

istringstream 对象可以绑定一行字符串,然后以空格为分隔符把该行分隔开来。

例子:

// test2.cpp : 定义控制台应用程序的入口点。
//学习string流 首先是istringstream

#include "stdafx.h"
#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
#include <vector>

using namespace std;

class PersonInfo
{
public:
	string name;
	vector<string> phones;
};
ostream & operator <<(ostream &os, PersonInfo & Info)
{
	cout<<"姓名:"<<Info.name<<" ";
	cout<<"电话号码:";
	vector<string>::iterator iter;
	for(iter=Info.phones.begin(); iter!=Info.phones.end(); iter++)
	{
		cout<<*iter<<" ";
	}
	return os;
}
int _tmain(int argc, _TCHAR* argv[])
{
	string path("phones.txt");
	ifstream File(path);
	string line;
	string number;
	vector<PersonInfo> People;
	while(getline(File,line))
	{
		/*cout<<line<<endl;*/
		PersonInfo Info;
		istringstream record(line);
		record>>Info.name;
		while(record>>number)
		{
			Info.phones.push_back(number);
		}
		People.push_back(Info);
	}
	//输出结果
	for(vector<PersonInfo>::iterator it=People.begin();it!=People.end(); it++ )
	{
		cout<<*it<<endl;
	}
	system("pause");
	return 0;
}
接下来是ostringstream, 把其他类型的数据写入流(往流中写入数据)
// test3.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	ostringstream ostr1;
	ostringstream ostr2("jiang");
	ostr1<<"shan"<<123<<endl;//将<<后面的所有文字写入到ostr1
	cout<<ostr1.str();//用方法str()将缓冲区的内容复制到一个string对象中,并返回
	//在使用put()方法时,先查看put pointer的值,防止误写
	int curPos=ostr2.tellp();
	cout<<"curPos = "<<curPos<<endl;
	ostr2.seekp(2);//手动设置put pointer的值
	ostr2.put('g');//在put pointer的位置上写入'g',并将put pointer指向下一个字符位置
	cout<<ostr2.str()<<endl;
	//重复使用同一个ostringstream对象时,建议
	//1.调用clear()清除当前错误控制状态
	//2.调用str("")将缓冲区清零,清除脏数据
	ostr2.clear();
	ostr2.str("");
	cout<<ostr2.str()<<endl;
	ostr2.str("jiang");
	cout<<ostr2.str()<<endl;
	ostr2<<"jiangshan";
	cout<<ostr2.str()<<endl;
	ostr2<<"js";
	cout<<ostr2.str()<<endl;
	string ss=ostr2.str();
	const char *buf=ss.c_str();
	cout<<buf<<endl;
	
	system("pause");
	return 0;
}
stringstream既可以像istringstream那样使用,又可以像ostringstream那样使用。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值