//string中不是靠'\0'来区分结束,是靠空格
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <map>
#include <stdlib.h>
using namespace std;
class WordStatic
{
private:
string _filename;
vector<string> _line;
map<string,vector<int> > map_word;
public:
void get_file(string file);
void read_file();
void search_word(string);
void search_line(int);
};
void WordStatic::get_file(string file)
{
_filename = file;
}
void WordStatic::read_file()
{
ifstream ifs(_filename.c_str());
if(!ifs.good())
{
cout<<"ifstream open error!"<<endl;
exit(-1);
}
string line;
string word;
int i,j,cnt=0;
while(getline(ifs,line))
{
_line.push_back(line);
cnt++;
istringstream iss(line);
while(iss >> word)
{
for(i=0,j=0;word[i]!='\0';++i)
{
if((word[i]>='a'&&word[i]<='z')||(word[i]>='A'&&word[i]<='Z'))
{
word[j]=word[i];
j++;
}
}
word[j]='\0';
if(j>0&&(map_word[word].empty()))
{
map_word[word].push_back(1);
map_word[word].push_back(cnt);
}
else if(j>0&&(!map_word[word].empty()))
{
++(map_word[word].front());
if(map_word[word].back()!=cnt)
map_word[word].push_back(cnt);
}
}
}
ifs.close();
}
void WordStatic::search_word(string str)
{
vector<int>::iterator i=map_word[str].begin();
cout<< str <<" occurs "<<*i<<" times "<<endl;
for(i=map_word[str].begin()+1;i!=map_word[str].end();++i)
{
cout<<"(line "<<*i<<" ) "<< _line[*i-1]<<endl;
}
}
void WordStatic::search_line(int n)
{
cout<<_line[n-1]<<endl;
}
|
int main()
{
WordStatic WS;
string s1;
cout<<"please enter file name:";
cin>>s1;
WS.get_file(s1);
cout<<"load……"<<endl;
WS.read_file();
char ch;
do
{
cout<<"select by word or line-number?";
string s2;
cin>>s2;
if(s2=="word")
{
cout<<"please enter the word:";
string s3;
cin>>s3;
system("cls");
WS.search_word(s3);
}
else if(s2=="line_number")
{
cout<<"please enter a line number:";
int n;
cin>>n;
system("clear");
WS.search_line(n);
}
cout<<"go on search?(y or n):";
cin>>ch;
}while(ch=='y');
return 0;
}
|