IO库 8.4

题目:编写函数,以读模式打开一个文件,将其内容读入到一个string的vector中,将每一行作为一个独立的元素存于vector中。

 1 #include <iostream>
 2 #include <fstream>
 3 #include <string>
 4 #include <vector>
 5 using namespace std;
 6 
 7 void ReadFileToVec(const string& fileName, vector<string>& vec)
 8 {
 9     ifstream ifs(fileName);
10     if (ifs) {
11         string buf;
12         while (getline(ifs, buf)) {
13             vec.push_back(buf);
14         }
15     }
16 }
17 
18 int main()
19 {
20     vector<string> vec;
21     ReadFileToVec("data.txt", vec);
22     for (const auto& str : vec) 
23         cout << str << endl;
24     }
25     return 0;
26 }

 

posted @ 2016-01-07 15:35  jasaiq  阅读(152)  评论(0编辑  收藏  举报