/*
*Copyright (C) 2014,烟台大学计算机学院
*All rights reserved.
*文件名称 :mian.cpp
*作 者 :韩娟
*完成日期 :2014年12月23日
*版 本 号 :v1.0
*
*问题描述 :做一个简单的电子词典。在文件dictionary.txt中,保存的是英汉对照的一个词典,词汇量近8000个,英文、中文释义与词性间用’\t’隔开。
编程序,由用户输入英文词,显示词性和中文释义。
提示1:定义一个Word结构体表示一个词条,其中的数据成员string english; 表示英文单词,string chinese;表示对应中文意思,string word_class;表示该词的词性;定义Word words[8000]存放所有词条成员,int wordsNum;表示词典中的词条数。
提示2:文件中的词汇已经排序,故在查找时,用二分查找法提高效率。
提示3:这样的项目,相关功能用函数实现,最好用多文件的形式组织
提示4:本项目的参考界面和未来的界面可以是下面的样子。不过暂时黑框框吧。。
*输入描述 :略
*程序输出 :略
*/
#include <fstream>
#include<iostream>
#include<string>
#include<cstdlib>
using namespace std;
//定义词条类
struct Word
{
string english;
string chinese;
string word_class;
};
Word words[8000]; //将词典数组设置成全局数组
int wordsNum=0; //词典中的词条数目
/*从文件中将词读到字典中*/
void readDictionary()
{
string e,c,wc;
//将文件中的数据读入到对象数组中
ifstream infile("dictionary.txt",ios::in); //以输入的方式打开文件
if(!infile) //测试是否成功打开
{
cerr<<"dictionary open error!"<<endl;
exit(1);
}
while (!infile.eof())
{
infile>>words[wordsNum].english;
infile>>words[wordsNum].chinese;
infile>>words[wordsNum].word_class;
++wordsNum;
}
infile.close();
}
int BinSeareh(int low, int high, string key)
{
int mid;
while(low<=high)
{
mid=(low + high) / 2;
if(words[mid].english==key)
{
return mid; //查找成功返回
}
if(words[mid].english>key)
high=mid-1; //继续在w[low..mid-1]中查找
else
low=mid+1; //继续在w[mid+1..high]中查找
}
return -1; //当low>high时表示查找区间为空,查找失败
}
void searchWord(string key)
{
int low=0,high=wordsNum-1; //置当前查找区间上、下界的初值
int index=BinSeareh(low, high, key);
if(index>=0)
cout<<key<<"--->"<<words[index].word_class+"\t"<<words[index].chinese;
else
cout<<"查无此词";
cout<<endl<<endl;
}
int main( )
{
readDictionary();
string key;
do
{
cout<<"请输入待查询的关键词(英文),0000结束:"<<endl;
cin>>key;
if (key!="0000")
{
searchWord(key);
}
}
while(key!="0000");
cout<<"欢迎再次使用!"<<endl<<endl;
return 0;
}
知识点总结 :
原来写过一个电子词典的,但是结构板的比较简单,要记得二分法。
学习心得 :
结构体好方便。