#include<iostream>
#include<fstream>
#include<vector>
#include<string>
#include<set>
#include<map>
#include<sstream>
using namespace std;
//功能实现:
//输入要查找的文件名和要查找的单词,显示该单词在文件中每一行出现的次数,行号按升序排列
//文本查询类
class TextQuery
{
private:
string filename; //文件名
fstream file;
vector<string>filecopy; //用于存放文件,文件每一行放入filecopy对应的元素中
map<int,int>rowcnt; //关键字是行号,关联值是出现次数
bool Query(string word); //查询函数,给定单词word,查找它在每一行出现的次数
public:
TextQuery(string name);
void Query_result(string word); //显示查询的结果
};
TextQuery::TextQuery(string name)
{
this->file.open(name.c_str());
if(!this->file)
{
cerr<<"文件不存在!"<<endl;
return;
}
this->filename=name;
string line;
while(getline(this->file,line))
{
this->filecopy.push_back(line); //将文件每一行加入到filecopy中
}
}
bool TextQuery::Query(string word)
{
vector<string>::const_iterator it;
bool occur=false; //表示在filecopy中是否出现要查询的单词
for(it=filecopy.begin();it!=filecopy.end();it++)
{
stringstream ss(*it); //ss用于将句子分解为单词
int row=it-filecopy.begin(); //行号
string str; //str存放copyfile每一行的单词
int cnt=0; //word在该行中出现的次数
while(ss>>str)
{
if(word==str) //在该行出现了要查找的单词
{
cnt++;
occur=true;
}
}
if(cnt) rowcnt.insert(make_pair(row,cnt));
}
return occur;
}
void TextQuery::Query_result(string word)
{
if(Query(word)==false)
{
cerr<<word<<"没有出现在文件中"<<endl;
return;
}
map<int,int>::const_iterator it;
for(it=rowcnt.begin();it!=rowcnt.end();it++)
{
cout<<"Line"<<it->first<<" "<<it->second<<"次"<<": "<<filecopy[it->first]<<endl;
}
}
void main()
{
string filename;
cout<<"请输入要查询的文件名:";
cin>>filename;
TextQuery textquery(filename);
string word;
cout<<"请输入要查询的单词:";
cin>>word;
textquery.Query_result(word);
}