C++第15周项目5——-电子词典

来源:互联网 发布:直销会员管理系统 php 编辑:程序博客网 时间:2024/04/28 16:49

课程首页地址:http://blog.csdn.net/sxhelijian/article/details/7910565


【项目5-电子词典】:做一个简单的电子词典。在文件dictionary.txt中(点此链接下载)作为调试,保存的是英汉对照的一个词典,词汇量近8000个,英文与释义间用’\t’隔开。编程序,将文件中的内容读到两个数组e[]和c[]中,分别代表英文和中文,由用户输入英文词,显示中文意思。运行程序后,支持用户连续地查词典,直到输入“0000”结束,如下图:
      
  提示:文件中的词汇已经排序,故在查找时,用二分查找法提高效率。


参考解答:

#include <fstream>#include<iostream>#include<cstdlib>#include<string>using namespace std;string e[8000],c[8000]; //英文和中文数组,要由文件中读入int wordsNum=0; //词库中实际的词汇条数int BinSeareh(int low, int high, string k);int main( ){ string key;      //查询关键词//将文件中的数据读入到对象数组中ifstream infile("dictionary.txt",ios::in);  //以输入的方式打开文件if(!infile)       //测试是否成功打开{cerr<<"open error!"<<endl;exit(1);}while (infile>>e[wordsNum]>>c[wordsNum])  //读取成功,则重复从文件中读{++wordsNum;}infile.close();//输入待查关键词并用二分查找法进行查询do{cout<<"请输入要查的词(0000结束):";cin>>key;if (key=="0000")break;else{int low=0,high=wordsNum-1;  //置当前查找区间上、下界的初值int index=BinSeareh(low, high, key);if (index == -1)cout<<"查无此词!"<<endl<<endl;elsecout<<key<<"的中文意思是:"<<c[index]<<endl<<endl;}}while(1);cout<<"欢迎再次使用!"<<endl<<endl;return 0;}//二分查找,结果为所查词在数组中的下标int BinSeareh(int low, int high, string k){int mid;while(low<=high){mid=(low + high) / 2;if(e[mid]==k){return mid; //查找成功返回}if(e[mid]>k)high=mid-1; //继续在e[low..mid-1]中查找elselow=mid+1; //继续在e[mid+1..high]中查找}return -1; //当low>high时表示查找区间为空,查找失败}




原创粉丝点击