第十七周 【项目7-电子词典结构体版】
问题及代码:
/*
*Copyright (c) 2014,烟台大学计算机学院
*ALL right reserved
*文件名:电子词典
*作者;童宇
*完成日期:2014年12月22日
*版本号v1.0
*问题描述:电子词典
*输入描述:输入一个英语单词
*程序输出:输出它的词性以及中文含义
*/
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
struct Word
{
string english;
string chinese;
string word_class;
};
int Middle (Word [],string word,int left,int right);
int main()
{
int i,j,wordsNum=0,get;
string in;
Word words[8000];
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].word_class)
{
++wordsNum;
++i;
}
infile.close();
int left=0,right=wordsNum;
while(in!="0")
{
cout<<"请输入想查询的单词\n输入0结束!\n";
cin>>in;
get=Middle(words,in,left,right);
if(get!=-1)
cout<<" "<<words[get].word_class<<"\t"<<words[get].chinese<<endl<<endl;
else
{
cout<<"该词典中没有这个单词!\n";
}
}
return 0;
}
int Middle (Word words[],string word,int left,int right)
{
while(left<=right)
{
int half=(left+right)/2;
if(words[half].english==word)
{
return half;
}
else if(words[half].english>word)
{
right=half-1;
}
else
{
left=half+1;
}
}
return -1;
}
运行结果:
还没有评论,来说两句吧...