/*设计一数据结构,实现对单词(限于a到z的26个字母)的存储,并可实现查询,如输入"ab",则返回所有以ab开头的单词.
在偶的程序里,我是打开一个文件,然后从文件中读取单词,核心技术还是使用strtok,用strtok分离出单词后,存在自定义的数据结构里面。最终由用户输入前面的几个字母,进行查询输出*/
#include<iostream>
#include<vector>
#include<fstream>
using namespace std;
char seps[] = " ,/t/"/n.?";
char *token;
typedef class st
{
public:
int co ; //the couter of words.
string str; //store the word.
st():co(0),str(""){ }
}search_word;
int main()
{
vector<search_word> vec;
st word;
ifstream ifs("Test.txt");
if(ifs == NULL)
{
cerr<<"The file was not opened."<<endl;
exit(1);
}
string strTemp;
string src;
while(getline(ifs,strTemp))
{
src += strTemp;
}
cout<<src<<endl;
cout<<"=========================================="<<endl;
int si = src.size();
char *pstr = new char[si +1];
strcpy(pstr,src.c_str());
token = strtok(pstr,seps);
while(token != NULL)
{
strTemp = token;
word.str = strTemp;
++word.co;
vec.push_back(word);
token = strtok(NULL,seps);
}
vector<search_word>::iterator ite;
for(ite = vec.begin();ite != vec.end();++ite)
{
cout<<(*ite).str<<" ";
}
cout<<endl<<endl;
cout<<"The number of the words is : "<<word.co<<endl;
string alphas;
bool successful = false;
cout<<"You can search words."<<endl;
cout<<"Please input the front alphas."<<endl;
cin>> alphas;
int sa = alphas.size();
for(ite = vec.begin();ite != vec.end();++ite)
{
strTemp = ((*ite).str).substr(0,sa);
if( strTemp == alphas)
{
successful = true;
cout<<(*ite).str<<" ";
}
}
cout<<endl<<endl;
if(!successful)
{
cout<<"I am sorry.I can't find some words that you want ."<<endl;
}
delete []pstr;
system("pause");
return 0;
}