Loading

C++Primer笔记——文本查询程序(原创,未使用类)

 

 

 

 1 #include <iostream>
 2 #include <vector>
 3 #include <set>
 4 #include <map>
 5 #include <fstream>
 6 #include <sstream>
 7 #include <string>
 8 
 9 using namespace std;
10 
11 int main()
12 {
13     ifstream in;
14     in.open("C:\\Users\\HP\\Desktop\\passage.txt");
15     vector<string>row;                   //使用vector<string>来保存整个输入文件的一份拷贝,输入文件的每行保存为其中的每一个元素
16     map<string, set<int>>word_and_row;   //使用map将每个单词与它出现的行号set关联起来,使用set可以保证行号不会重复且升序保存
17     string s;
18     while (getline(in, s))
19     {
20         row.push_back(s);
21     }
22     for (size_t i = 0; i < row.size(); ++i)
23     {
24         string word;
25         istringstream read(row[i]);     //使用istringstream来将每行分解为单词
26         while (read >> word)
27             word_and_row[word].insert(i);
28     }
29     
30     string s1;                          //s1为待查找的单词。注意:待查找的单词不能与句号或逗号连在一起!
31     while (cin >> s1 && s1 != "q" )     //输入q时终止输入
32         if (word_and_row.find(s1) != word_and_row.end())
33         {
34             int i = word_and_row[s1].size();
35             cout << s1 << " occurs " << i << " times" << endl;
36             for (auto d : word_and_row[s1])
37                 cout << "(line " << d + 1 << ") " << row[d] << endl;
38             
39         }
40         else
41         {
42             cout << "This word can not be found in this passage! Please input a word again: " << endl;    
43         }
44     in.close();
45 
46     return 0;
47 }

 

posted @ 2018-07-10 17:00  拾月凄辰  阅读(300)  评论(0编辑  收藏  举报