#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <fstream>
#include <sstream>
#include <string> using namespace std; int main()
{
ifstream in;
in.open("C:\\Users\\HP\\Desktop\\passage.txt");
vector<string>row; //使用vector<string>来保存整个输入文件的一份拷贝,输入文件的每行保存为其中的每一个元素
map<string, set<int>>word_and_row; //使用map将每个单词与它出现的行号set关联起来,使用set可以保证行号不会重复且升序保存
string s;
while (getline(in, s))
{
row.push_back(s);
}
for (size_t i = ; i < row.size(); ++i)
{
string word;
istringstream read(row[i]); //使用istringstream来将每行分解为单词
while (read >> word)
word_and_row[word].insert(i);
} string s1; //s1为待查找的单词。注意:待查找的单词不能与句号或逗号连在一起!
while (cin >> s1 && s1 != "q" ) //输入q时终止输入
if (word_and_row.find(s1) != word_and_row.end())
{
int i = word_and_row[s1].size();
cout << s1 << " occurs " << i << " times" << endl;
for (auto d : word_and_row[s1])
cout << "(line " << d + << ") " << row[d] << endl; }
else
{
cout << "This word can not be found in this passage! Please input a word again: " << endl;
}
in.close(); return ;
}