做一个简单的电子词典。在文件dictionary.txt中,保存的是英汉对照的一个词典,词汇量近8000个,英文、中文释义与词性间用’\t’隔开。
(1)编程序,由用户输入英文词,显示词性和中文释义。
提示1:如果要用OOP完成这个词典(当然也可以用OO方法实现),可以定义一个Word类表示一个词条,其中的数据成员string english; 表示英文单词,string chinese;表示对应中文意思,string word_class;表示该词的词性;还可以定义一个Dictionary类,用来表示词典,其中Word
words[8000]成员表示词典中的词条,int wordsNum;表示词典中的词条数,在构造函数中从文件读入词条,而专门增加一个成员函数用于查单词。
提示2:文件中的词汇已经排序,故在查找时,用二分查找法提高效率。
提示3:这样的项目,最好用多文件的形式组织
代码如下:
/*
*Copyright(c)2014,烟台大学计算机学院
*All rights reserved.
*文件名称:test.cpp
*作者:满星辰
*完成日期:2015年 6月 9日
*版本号:v1.0
*
*/
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <cstring>
using namespace std;
class Word
{
public:
string word_class;
string chinese;
string english;
};
class dictionary
{
public:
dictionary();
int Tsearch(int low,int high,string word);
void view(string word);
private:
Word words[8000];
int word_num;
};
dictionary::dictionary()
{
word_num=0;
ifstream infile("dictionary.txt",ios::in);
//测试是否成功打开,打开失败时(如要读的数据文件不存在)退出
if(!infile)
{
cerr<<"open error!"<<endl;
exit(1);
}
while(!infile.eof())
{
infile>>words[word_num].english>>words[word_num].chinese>>words[word_num].word_class;
++word_num;
}
infile.close(); //读入完毕要关闭文件
}
int dictionary::Tsearch(int low,int high,string word)
{
int mid;
while(low<=high)
{
mid=(low+high)/2;
if(words[mid].english==word)
{
return mid;
}
if(words[mid].english>word)
high=mid-1;
else
low=mid+1;
}
return 0;
}
void dictionary::view(string word)
{
int low=0,high=word_num-1;
int index=Tsearch(low,high,word);
if(index==0)
cout<<"本词典未收录该词汇"<<endl<<endl;
else
cout<<words[index].english<<'\t'<<words[index].chinese<<'\t'<<words[index].word_class<<endl<<endl;
}
int main()
{
dictionary d;
string word;
do
{
cout<<"请输入要查询的词(0000结束):";
cin>>word;
if(word=="0000")
break;
else
{
d.view(word);
}
}
while(word!="0000");
}
图片:
心得:
参考了一下以前做过差不多的,So感觉没什么不同,还是挺容易的,就是一开始怎么分配不好想