天天看点

C++ primer(第五版) 练习 8.4 个人 code



C++ primer(第五版) 练习 8.4

题目:编写函数,以读模式打开一个文件,将其内容读入到一个string的vector中

将每一行作为一个独立的元素存于vector中。

答:

#include <iostream>
#include <fstream>
#include <vector>
#include <string>

using std::ifstream;
using std::vector;
using std::string;
using std::getline;
using std::cout;
using std::endl;

int main()
{
	vector<string> vstr;
	string tmpstr;
	ifstream myif;
	myif.open("1.txt");
	vector<string>::size_type i = 0;
	if (myif)
	{
		while (getline(myif,tmpstr))
		{
			vstr.push_back(tmpstr);
			i++;
		}

	}
	i = 0;
	for (; i != vstr.size(); ++i)
	{
		cout << "第" << i  << "行的内容为:" << vstr[i] << endl;
	}

	return 0;

}
           

1.txt文件内容:

We study English every day. So of course we should know something about England.
我们每天都学习英语,因此我们当然应该知道一些有关英国的事。
England is an island in Europe. The nearest country is France, which is 20 miles away.The capital city is London, which is in the southeast of England. It is a city with a long history.
英国是欧洲的一个岛国,最近的邻国是法国,有20英里远。英国首都是伦敦,它在英国的东南部,是一座具有悠久历史的城市。
In England, people often talk about the weather, because they can have four seasons in one day.They can have summer in winter or have winter in summer

           

执行结果:

C++ primer(第五版) 练习 8.4 个人 code

继续阅读