C++primer 8.3.1节练习

练习8.9

 1 #include <iostream>
 2 #include <sstream>
 3 #include <string>
 4 #include <vector>
 5 using namespace std;
 6 
 7 istream &readPrint(istream &is);
 8 
 9 istream & readPrint(istream & is)
10 {
11     auto old_state = cin.rdstate();
12     string i;
13     while (!is.eof())
14     {
15         is >> i;
16         cout << i << " ";
17     }
18     cin.setstate(old_state);
19     return is;
20     // TODO: 在此处插入 return 语句
21 }
22 
23 int main()
24 {
25     string str{"asdhaskdhasd"};
26     istringstream record(str);
27     readPrint(record);
28     system("pause");
29     return 0;
30 }

练习8.10

 1 #include <iostream>
 2 #include <sstream>
 3 #include <string>
 4 #include <vector>
 5 #include <fstream>
 6 using namespace std;
 7 
 8 
 9 int main()
10 {
11     string line, word;
12     vector <string> str;
13     vector <string> str1;
14     ifstream in("title.txt");
15     ofstream out("answer.txt", ofstream::app);
16     while (!in.eof())
17     {
18         getline(in, line);
19         str.push_back(line);
20     }
21     for (auto it = str.begin(); it != str.end(); it++)
22     {
23         istringstream record(*it);
24         while ( !record.eof() )
25         {
26             record >> word;
27             str1.push_back(word);
28         }
29     }    
30     for (auto c : str1)
31         out << c << endl;
32     system("pause");
33     return 0;
34 }

练习8.11

 1 #include <iostream>
 2 #include <sstream>
 3 #include <string>
 4 #include <vector>
 5 #include <fstream>
 6 using namespace std;
 7 
 8 struct PersonInfo {
 9     string name;
10     vector<string> phones;
11 };
12 
13 
14 int main()
15 {
16     string line, word;
17     PersonInfo info;
18     vector <PersonInfo> people;
19     istringstream record;
20     while (getline(cin, line))
21     {
22         PersonInfo info;
23         record.str(line);
24         record >> info.name;
25         while (record >> word)
26             info.phones.push_back(word);
27         people.push_back(info);
28     }
29     system("pause");
30     return 0;
31 }

使用stm.str(s)这个函数,将line的值拷贝到record中;

练习8.12

程序的作用就是往里面写入数据,所以不需要初始化。

posted @ 2017-08-09 14:25  五月份小姐  阅读(387)  评论(0编辑  收藏  举报