问题及代码:
/*
*Copyright (c) 2016,烟台大学计算机学院
*All rights reserved.
*文件名称:main.cpp
*作 者:李磊涛
*完成时间:2016年6月23日
*版 本 号:v1.0
*
*问题描述:项目-OOP版电子词典。
*输入描述:要查找单词。
*程序输出:汉语意思。
*/
#include <fstream>
#include<iostream>
#include<string>
#include<cstdlib>
using namespace std;
class word
{
public:
void set(string a,string b,string c);
int compare(string);
string getchinese();
string getword_class();
private:
string english;
string chinese;
string word_class;
};
void word::set(string a,string b,string c)
{
english=a;
chinese=b;
word_class=c;
}
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 sword(string k);
private:
int BinSeareh(int low, int high, string k);
int wordsNum;
word words[8000]; //用于保存词库
};
Dictionary ::Dictionary()
{
string a,b,c;
wordsNum=0;
ifstream infile("dictionary.txt",ios::in); //以输入的方式打开文件
if(!infile) //测试是否成功打开
{
cerr<<"dictionary open error!"<<endl;
exit(1);
}
while (!infile.eof())
{
infile>>a>>b>>c;
words[wordsNum].set(a,b,c);
++wordsNum;
}
infile.close();
}
int Dictionary::BinSeareh(int low, int high, string key)
{
int mid;
while(low<=high)
{
mid=(low + high) / 2;
if(words[mid].compare(key)==0)
{
return mid; //查找成功返回
}
if(words[mid].compare(key)>0)
high=mid-1; //继续在w[low..mid-1]中查找
else
low=mid+1; //继续在w[mid+1..high]中查找
}
return -1; //当low>high时表示查找区间为空,查找失败
}
void Dictionary::sword(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 main( )
{
Dictionary dict;
string key;
do
{
cout<<"请输入待查询的关键词(英文),0000结束:"<<endl;
cin>>key;
if (key!="0000")
{
dict.sword(key);
}
}
while(key!="0000");
cout<<"欢迎再次使用!"<<endl<<endl;
return 0;
}
运行结果:
通过该程序,强化了我对简单程序结构的认识。
学习心得:
期间有很多小错误,要继续写程序争取早日掌握C++。
问题及代码:
运行结果:
通过该程序,强化了我对简单程序结构的认识。
学习心得:
期间有很多小错误,要继续写程序争取早日掌握C++。