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那样使用。