做一个简单的电子词典。在文件dictionary.txt中,保存的是英汉对照的一个词典,词汇量近8000个,英文、中文释义与词性间用’\t’隔开。
编程序,由用户输入英文词,显示词性和中文释义。
提示1:定义一个Word结构体表示一个词条,其中的数据成员string english; 表示英文单词,string chinese;表示对应中文意思,string word_class;表示该词的词性;定义Word words[8000]存放所有词条成员,int wordsNum;表示词典中的词条数。
提示2:文件中的词汇已经排序,故在查找时,用二分查找法提高效率。
运行结果:
编程序,由用户输入英文词,显示词性和中文释义。
提示1:定义一个Word结构体表示一个词条,其中的数据成员string english; 表示英文单词,string chinese;表示对应中文意思,string word_class;表示该词的词性;定义Word words[8000]存放所有词条成员,int wordsNum;表示词典中的词条数。
提示2:文件中的词汇已经排序,故在查找时,用二分查找法提高效率。
提示3:这样的项目,相关功能用函数实现,最好用多文件的形式组织
/*
* Copyright (c) 2014,烟台大学计算机学院
* All right reserved.
* 作者:邵帅
* 文件:demo.cpp
* 完成时间:2014年12月21日
* 版本号:v1.0
*/
#include <iostream>
#include <string>
#include <fstream>
#include<cstdlib>
using namespace std;
int binary_search(string key,int n);
struct Word
{
string english;
string chinese;
string word_class;
};
Word word[8000];
int main()
{
int wordsNum=0;
string key;
int tem;
//打开文件
ifstream infile("dictionary.txt",ios::in);
if (!infile)
{
cout<<"打开文件失败!";
exit(1);
}
while (infile>>word[wordsNum].english)
{
infile>>word[wordsNum].chinese;
infile>>word[wordsNum].word_class;
wordsNum++;
}
infile.close(); //关闭文件
cout<<"欢迎使用本词典 (0000)退出"<<endl;
while (1)
{
cin>>key;
if(key=="0000")
break;
tem=binary_search(key,wordsNum);
if (tem==-1)
{
cout<<"└─────查无此词"<<endl;
continue;
}
else
cout<<"└─────"<<word[tem].word_class<<word[tem].chinese<<endl;
}
}
int binary_search(string key,int n) //二分法查找
{
int i=-1;
int low=0,high=n-1,mid;
while (low<=high)
{
mid=(low+high)/2;
if (word[mid].english==key)
{
return mid;
}
else if (word[mid].english>key)
high=mid-1;
else
low=mid+1;
}
return i;
}
运行结果:
@ Mayuko