fstream,sstream,使用(习题8.16)

读出cin中残存的回车换行符应使用:getline(cin,s);

#include<iostream>
#include<fstream>
#include<sstream>
#include<string>
#include<vector>
using namespace std;

ofstream & write(ofstream &out)
{
	string s;
	getline(cin,s);  //读出cin中的回车换行符

	string line;
	cout<<"Enter some lines of text:"<<endl;
	while(getline(cin,line))
		out<<line<<endl;
	return out;
}

ifstream & read(ifstream &in,vector<string> &lineVec)
{
	//把文件中的数据按行写入容器中
	string line;
	while(getline(in,line))
		lineVec.push_back(line);
	return in;
}

int main()
{
	string fileName;
	cout<<"Enter a file name:"<<endl;
	cin>>fileName;

	//open file
	ofstream outFile(fileName.c_str());
	write(outFile);  //对文件进行写操作
	outFile.close();

	vector<string> lineVec;
	ifstream inFile(fileName.c_str());
	read(inFile,lineVec);  //对文件进行读操作
	inFile.close();

	//使用istringstream对象每次读取一个单词的形式输出容器元素
	cout<<"按行读取容器中的元素,以每个单词的形式输出每行"<<endl;
	for(vector<string>::iterator it=lineVec.begin();it!=lineVec.end();++it)
	{
		istringstream isstr(*it);
		string word;
		while(isstr>>word)
			cout<<word<<endl;
		isstr.clear();
		cout<<endl;
	}

	return 0;
}

zhaobin@debian:~$ ./t
Enter a file name:
ooo
Enter some lines of text:
justin bibber baby
adele someone like you
beyonce if i were a boy
按行读取容器中的元素,以每个单词的形式输出每行
justin
bibber
baby

adele
someone
like
you

beyonce
if
i
were
a
boy

你可能感兴趣的:(C++,vector,istringstream)