问题及代码:
/*
*Copyright(c)2014,烟台大学计算机学院
*Allrights reserved.
*文件名称:MADE88.cpp
*作 者:孙化龙
*完成日期:2014年12月23日
*版 本 号:v1.0
*
*问题描述:做一个简单的电子词典
*/
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cstring>
using namespace std;
struct Word
{
string english;
string chinese;
string wordclass;
};
int main()
{
Word words[8000];
int i,wordsNum=0;
ifstream infile("dictionary.txt",ios::in); //以输入的方式打开文件
if(!infile) //测试是否成功打开
{
cerr<<"open error!"<<endl;
exit(1);
}
i=0;
while(infile>>words[i].english>>words[i].chinese>>words[i].wordclass)
{
++wordsNum;
++i;
}
infile.close();
string key="a";
while(key!="0000")
{
cout<<"输入要查找的词(0000退出):";
cin>>key;
int low=0,high=wordsNum-1,mid;
while(low<=high)
{
mid=(low+high)/2;
if(words[mid].english==key)
{
cout<<words[mid].english<<"<---"<<words[mid].wordclass<<words[mid].chinese<<endl;
break;
}
else if(words[mid].english>key)
high=mid-1;
else if(words[mid].english<key)
low=mid+1;
}
if(low>high&&key!="0000")
cout<<"查无此词"<<endl;
}
return 0;
}
运行结果: