练习8.4,8.5

//练习8.4 编写函数,以读模式打开一个文件,将其内容读入到一个string的vector中,
//将每一行作为一个独立的元素存于vector中,改写上面的程序,将每个单词作为一个独立的元素进行存储


#include
#include
#include
#include
#include
using namespace std;


int main(int argc, char *argv[])
{
	ifstream fs;
	fs.open("text.txt",ifstream::in);//创建一个输入文件流对象,并以读的形式打开
	vector  lines1,lines2;
	string line,word;
	while (getline(fs,line))
	{
		cout << line;//getline 会自动舍弃换行符,凡是空格会留着
		lines1.push_back(line);
		istringstream ss(line);
		while (ss >> word)
		{
			lines2.push_back(word);
		}
	}
	for (vector::iterator it = lines1.begin(); it != lines1.end(); ++it)
	{
		cout << *it << endl;
	}
	cout << "lines printing finishes!" << endl;
	for (vector::iterator it = lines2.begin(); it != lines2.end(); ++it)
	{
		cout << *it << endl;
	}
	cout << "lines printing finishes!" << endl;
	system("pause");
	return 0;
}

你可能感兴趣的:(c++,primer,5th,练习题)