问题及代码:
/*
* Copyright (c) 2014, 烟台大学计算机学院
* All rights reserved.
* 文件名称:Project4.cpp
* 作 者:李楠
* 完成日期:2014年12月21日
* 版 本 号:v1.0
*
* 问题描述:做一个简单的电子词典。在文件dictionary.txt中,保存的是英汉对照的一个词典,词汇量近8000个,
英文与释义间用’\t’隔开。编程序,将文件中的内容读到两个数组e[]和c[]中,分别代表英文和中文,
由用户输入英文词,显示中文意思。运行程序后,支持用户连续地查词典,直到输入“0000”结束,
提示:文件中的词汇已经排序,故在查找时,用二分查找法提高效率。
* 输入描述:单词
* 程序输出:中文意思
*/
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
struct Word
{
string english;
string word_class;
string chinese;
};
Word words[8000];
int wordsNum=0;
int wsearch(int low,int high,string k);
int main()
{
string key;
ifstream infile("dictionary.txt",ios::in);
if(!infile)
{
cerr<<"open error!";
exit(1);
}
while(wordsNum<=8000)
{
infile>>words[wordsNum].english;
infile>>words[wordsNum].chinese;
infile>>words[wordsNum].word_class;
wordsNum++;
}
infile.close();
do
{
cout<<"请输入待查询的关键词(英文),0000结束:"<<endl;
cin>>key;
if(key=="0000")
break;
else
{
int low=0,high=wordsNum-1;
int index=wsearch(low,high,key);
if(index==-1)
cout<<"查无此词!"<<endl;
else
cout<<key<<"—>"<<words[index].word_class<<"\t"<<words[index].chinese<<endl<<endl;
}
}while(-1);
cout<<"欢迎再次使用!"<<endl;
return 0;
}
int wsearch(int low,int high,string k)
{
int mid;
while(low<=high)
{
mid=(low+high)/2;
if(words[mid].english==k)
return mid;
if(words[mid].english>k)
high=mid-1;
else
low=mid+1;
}
return -1;
}
运行结果:
知识点总结:
结构体版的电子词典是比原来的稍微简单点~
学习心得:
一定好好复习C++啊啊啊啊啊啊