C++primer 8.2.1节练习

练习8.4

 1 #include <string>
 2 #include <iostream>
 3 #include <vector>
 4 #include <fstream>
 5 
 6 using namespace std;
 7 
 8 void read(string s);
 9 
10 int main()
11 {
12     read("test.txt");
13     system("pause");
14     return 0;
15 }
16 
17 void read(string s)
18 {
19     string line;
20     vector<string> text;
21     ifstream in(s);
22     while (!in.eof())
23     {
24         getline(in, line);
25         text.push_back(line);
26     }
27     for (auto c : text)
28         cout << c << endl;
29 }

练习8.5

 1 #include <string>
 2 #include <iostream>
 3 #include <vector>
 4 #include <fstream>
 5 
 6 using namespace std;
 7 
 8 void read(string s);
 9 
10 int main()
11 {
12     read("title.txt");
13     system("pause");
14     return 0;
15 }
16 
17 void read(string s)
18 {
19     string line;
20     vector<string> text;
21     ifstream in(s);
22     while (!in.eof())
23     {
24         in >> line;
25         text.push_back(line);
26     }
27     for (auto c : text)
28         cout << c << endl;
29 }

练习8.6

 1 int main()                                                                            //main函数的部分需要改变
 2 {
 3     ifstream in("sales_data.txt");
 4     //改动地方,新增一个Sales_data.txt 
 5     Sales_data total;
 6     if (read(in, total)) {
 7         //read(cin,total); 变为read(in,total); 
 8         Sales_data trans;
 9         while (read(in, trans)) {
10             //read(cin, total); 变为read(in,total); 
11             if (total.isbn() == trans.isbn())
12                 total.combine(trans);
13             else
14             {
15                 print(cout, total) << endl;
16                 total = trans;
17             }
18         }
19         print(cout, total) << endl;
20     }
21     else {
22         cerr << "No data?!" << endl;
23     }
24     system("pause");
25     return 0;
26 }

 

posted @ 2017-08-08 21:16  五月份小姐  阅读(337)  评论(0编辑  收藏  举报