第十四周【项目3-OOP版电子词典】

来源:互联网 发布:北大青鸟java培训课程 编辑:程序博客网 时间:2024/05/18 03:23
  问题及代码:
/* 【项目3-OOP版电子词典】 *Copyright (c) 2014,烟台大学计算机学院 *ALL right reserved *文件名: 版电子词典 *作者;童宇 *完成日期:2015 年 6月 11日 *版本号v1.0 *问题描述:            编程序,由用户输入英文词,显示词性和中文释义。 *输入描述: *程序输出: */#include <fstream>#include<iostream>#include<string>#include<cstdlib>using namespace std;//定义词条类class Word{public:    void set(string e, string c, string wc);    int compare(string);  //英语部分与给定字符串比较,等于返回,大于返回,小于返回-1    string getChinese();    string getWord_class();private:    string english;    string chinese;    string word_class;};void Word::set(string e, string c, string wc){    english=e;    chinese=c;    word_class=wc;}int Word::compare(string k){    return english.compare(k);}string Word::getChinese(){    return chinese;}string Word::getWord_class(){    return word_class;}class Dictionary{public:    Dictionary();    void searchWord(string k);private:    int BinSeareh(int low, int high, string k);    int wordsNum;    Word words[8000]; //用于保存词库};Dictionary::Dictionary(){    string e,c,wc;    wordsNum=0;    ifstream infile("dictionary.txt",ios::in);    if(!infile)    {        cerr<<"dictionary open error!"<<endl;        exit(1);    }    while (!infile.eof())    {        infile>>e>>c>>wc;        words[wordsNum].set(e,c,wc);        ++wordsNum;    }    infile.close();}void Dictionary::searchWord(string k){    int low=0,high=wordsNum-1;    int index=BinSeareh(low,high,k);    if(index>=0)        cout<<k<<"--->"<<words[index].getWord_class()+"\t"<<words[index].getChinese();    else        cout<<"查无此词";    cout<<endl<<endl;}int Dictionary::BinSeareh(int low, int high, string k){    int m;    while (low<=high)    {        m=(low+high)/2;        if(words[m].compare(k)==0)        {            return m;        }        if(words[m].compare(k)>0)        {            high=m-1;        }        else            low=m+1;    }    return -1;}int main( ){    Dictionary dict;    string key;    do    {        cout<<"请输入待查询的关键词(英文),0000结束:"<<endl;        cin>>key;        if (key!="0000")        {            dict.searchWord(key);        }    }    while(key!="0000");    cout<<"欢迎再次使用!"<<endl<<endl;    return 0;}


运行结果:


0 0