項目要求
做一個簡單的電子詞典。在文件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 <cstdlib>
#include <fstream>
using namespace std;
const int wordsNum=8000;
class Word
{
public:
void setWord(string en,string ch,string wc)
{
chinese=ch;
english=en;
word_class=wc;
}
string get_english()
{
return english;
}
string get_chinese()
{
return chinese;
}
string get_word_class()
{
return word_class;
}
friend class Dictionary;
private:
string chinese;
string english;
string word_class;
};
class Dictionary
{
public:
int trans(string english,int low,int high);
void look_up();
void get_words();
friend class Word;
private:
Word words[8000];
};
int Dictionary::trans(string word,int low,int high)
{
int mid;
while(low<=high)
{
mid=(high+low)/2;
if (words[mid].get_english()==word)
return mid;
if (words[mid].get_english()<word)
low=mid+1;
else
high=mid-1;
}
return 0;
}
void Dictionary::get_words()
{
string ch,en,wc;
ifstream infile("dictionary.txt",ios::in);
if (!infile)
{
cerr<<"open error!"<<endl;
exit(1);
}
cout<<"opend success!"<<endl;
for (int i=0; i<wordsNum; i++)
{
infile>>en>>ch>>wc;
words[i].setWord(en,ch,wc);
}
infile.close();
}
void Dictionary::look_up()
{
string word;
int n;
do
{
cout<<endl<<"請輸入要查詢的單詞(輸入0000可退出本程序):";
cin>>word;
if (word=="0000")
break;
else
{
n=trans(word,0,wordsNum-1);
if (n==0)
cout<<"本詞典未收錄"<<word<<"含義。"<<endl;
else
cout<<words[n].get_english()<<"\t"<<words[n].get_chinese()
<<"\t"<<words[n].get_word_class()<<endl;
}
}
while (word!="0000");
}
int main()
{
Dictionary dic;
Word w;
cout<<"歡迎使用本詞典查詢系統!詞典載入中…"<<endl;
dic.get_words();
dic.look_up();
return 0;
}
運行結果
學習心得
這個程序居然做了一上午…不過很有成就感
有機會一定做成GUI
1.二分法:
int Dictionary::trans(string word,int low,int high)
{
int mid;
while(low<=high)
{
mid=(high+low)/2;
if (words[mid].get_english()==word)
return mid;
if (words[mid].get_english()<word)
low=mid+1;
else
high=mid-1;
}
return 0;
}
2.記得 infile>>english的寫法
3. const int wordsNum=8000;