第17周项目7-电子词典结构体版

来源:互联网 发布:小区车辆出入数据 编辑:程序博客网 时间:2024/06/08 18:24

问题及代码:

/**Copyright (c)2014,烟台大学计算机与控制工程学院*All rights reserved.*文件名称:word.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<cstdlib>using namespace std;struct word{    string english;    string chinese;    string word_class;} ;int main( ){    word words[8000];    int wordsnum=0;    string key;      //读入的成绩    //以输入的方式(ios::in)打开文件    ifstream infile("dictionary.txt",ios::in);    //测试是否成功打开,打开失败时(如要读的数据文件不存在)退出    if(!infile)    {    cerr<<"open error!"<<endl;        exit(1);    }    while (!infile.eof())    {        infile>>words[wordsnum].english;        infile>>words[wordsnum].chinese;            infile>>words[wordsnum].word_class;            wordsnum++;    }    infile.close();    //读入完毕一定要关闭文件cout<<"请输入要查的词(0000结束):";   while(cin>>key&&key!="0000")   {       int low=0,high=wordsnum-1,mid,index=-1;       while(low<=high)       {           mid=(low+high)/2;          if(words[mid].english==key)           {           index=mid;           break;           }           else if(words[mid].english>key)            high=mid-1;           else            low=mid+1;         }       if(index>=0)        cout<<key<<"的中文意思是:"<<words[index].chinese<<endl;        else        cout<<"查无此词!"<<endl;   }   return 0;}


运行结果;

0 0
原创粉丝点击