【项目3-OOP版电子词典】
做一个简单的电子词典。在文件dictionary.txt中,保存的是英汉对照的一个词典,词汇量近8000个,英文、中文释义与词性间用’\t’隔开。
(1)编程序,由用户输入英文词,显示词性和中文释义。
提示1:如果要用OOP完成这个词典(当然也可以用OO方法实现),可以定义一个Word类表示一个词条,其中的数据成员string english; 表示英文单词,string chinese;表示对应中文意思,string word_class;表示该词的词性;还可以定义一个Dictionary类,用来表示词典,其中Word words[8000]成员表示词典中的词条,int wordsNum;表示词典中的词条数,在构造函数中从文件读入词条,而专门增加一个成员函数用于查单词。
提示2:文件中的词汇已经排序,故在查找时,用二分查找法提高效率。
提示3:这样的项目,最好用多文件的形式组织
#include <iostream>
#include <fstream>
#include <cstring>
#include<cstdlib>
using namespace std;
class Word
{
private:
string english;
string chinese;
string word_class;
public:
void set(string e,string c,string w);
int compare(string w);
string getChinese();
string getEnglish();
string get_word_class();
};
void Word::set(string e,string c,string w)
{
english=e;
chinese=c;
word_class=w;
}
int Word::compare(string w)
{
return english.compare(w);
}
string Word::getChinese()
{
return chinese;
}
string Word::getEnglish()
{
return english;
}
string Word::get_word_class()
{
return word_class;
}
class Dictionary
{
private:
Word words[8000];
int wordsNum;
int search(int low,int high,string w);
public:
Dictionary();
void searchWord(string w);
};
Dictionary::Dictionary()
{
string e,c,w;
wordsNum=0;
ifstream infile("dictionary.txt",ios::in);
if(!infile)
{
cerr<<"dictionary open error!"<<endl;
exit(1);
}
while(!infile.eof())
{
infile>>e>>c>>w;
words[wordsNum].set(e,c,w);
wordsNum++;
}
infile.close();
}
int Dictionary::search(int low,int high,string w)
{
int mid;
while(low<=high)
{
mid=(low+high)/2;
if(words[mid].compare(w)==0)
{
return mid;
}
else if(words[mid].compare(w)>0)
high=mid-1;
else
low=mid+1;
}
return -1;
}
void Dictionary::searchWord(string key)
{
int low=0,high=wordsNum-1;
int k=search(low,high,key);
if(k>0)
cout<<key<<"<----"<<words[k].get_word_class()<<'\t'<<words[k].getChinese()<<endl;
else
cout<<"<----查无此词"<<endl;
cout<<endl;
}
int main()
{
Dictionary d;
string key;
do
{
cout<<"请输入想查询的单词,以0为结束:"<<endl;
cin>>key;
if(key!="0")
d.searchWord(key);
}
while(key!="0");
cout<<"欢迎下次使用!"<<endl;
return 0;
}
运行结果: