您的位置:首页 > 编程语言 > C语言/C++

第十六周C++【任务三】一个简单的电子词典

2012-06-04 22:28 330 查看
   【任务3】电子词典

做一个简单的电子词典。在文件dictionary.txt 中,保存的是英汉对照的一个词典,词汇量近8000 个,

英文、中文释义与词性间用’\t’隔开。建一个表示词条的类Word,Word 类的一个对象可以描述一个词,

类对象数组可以存储词库。将文件中的内容读到对象数组中,由用户输入英文词,显示中文释义。

提示:文件中的词汇已经排序,故在查找时,用二分查找法提高效率。

拓展1(选做):允许用户运行程序后,连续地查词典,直到输入”0000”结束。

拓展2(选做):试着做一个窗口版的电子词典。

拓展3(选做):使这个词典,读入一篇文章,输出其中的所有名词(或动词,或全部实词)。——
搜索引擎用类似的功能,用于筛去虚词,因为并不是所有词都值得索引。

#include <iostream>
using namespace std;
#include <fstream>
#include <string>
class Word
{
public:
void get_cixing(string cixing);
void get_chinese(string english);
void get_english(string chinese);
friend void find_word(Word *t);
friend void input_word(Word *t);
friend void output_word(Word *t);

private:
string cixing;
string english;
string chinese;
};
void Word::get_cixing(string cixing)
{
this->cixing = cixing;
}
void Word::get_chinese(string english)
{
this->english = english;
}
void Word::get_english(string chinese)
{
this->chinese = chinese;
}
void input_word(Word *t)
{
string cixing;
string english;
string chinese;
int i;
ifstream inFile("dictionary.txt",ios::in);
if(!inFile)
{
cerr<<"open error!"<<endl;
exit(1);
}
for(i=0;i<8000;++i)
{
inFile>>chinese;
t[i].get_chinese(chinese);

inFile>>cixing;
t[i].get_cixing(cixing);

inFile>>english;
t[i].get_english(english);
}

inFile.close();

}
void output_word(Word *t)
{
string cixing;
string english;
string chinese;
ofstream outFile("dic.txt",ios::out);
if(!outFile)
{
cerr<<"open dic.txt error!"<<endl;
exit(1);
}
for(int i=0;i<8000;++i)
{
outFile<<t[i].chinese;

outFile<<t[i].english;

outFile<<t[i].cixing;
}
outFile.close();

}

void find_word(Word *t)
{
int  f=0;
int  s=7999;
int mid=(f+s)/2;
string word;
cin>>word;

while(f<s&&t[mid].english!=word)
{
if(t[mid].english<word) f=mid+1;
if(t[mid].english>word) s=mid-1;
mid=f+(s-f)/2;
if(t[mid].english==word)
{
cout<<t[mid].chinese<<endl;
cout<<t[mid].cixing<<endl;
}

}
if(t[mid].english!=word)
cout<<"没有查到"<<endl;
}
int main()
{
Word t[8000];
input_word(t);
find_word(t);

output_word(t);
system("pause");
return 0;
}




 

积累经验:

 二分法是个难点,但有问题找百度,对解决问题很有帮助。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐