第17周项目7-电子词典结构体版
第17周项目7--电子词典结构体版
/* * Copyright (c) 2014, 烟台大学计算机学院 * All rights reserved. * 文件名称:test.cpp * 作 者:刘畅 * 完成日期:2014 年 12 月 23 日 * 版 本 号:v1.0 * * 问题描述:做一个简单的电子词典。在文件dictionary.txt中,保存的是英汉对照的一个词典,词汇量近8000个,英文、中文释义与词性间用’\t’隔开。 编程序,由用户输入英文词,显示词性和中文释义。。 * 输入描述:输入英文单词。 * 程序输出:显示词性和中文释义。
#include <fstream> #include <iostream> #include <string> #include <cstdlib> using namespace std; struct Word { string english; string chinese; string word_class; }; const int num=8000; Word word[num]; int BinarySearch(int max,int min,string key); int main() { string key; int wordNum=0; ifstream infile("dictionary.txt",ios::in); if (!infile) { cerr<<"open error!"<<endl; exit(1); } while (infile>>word[wordNum].english>>word[wordNum].chinese>>word [wordNum].word_class) { ++wordNum; } infile.close(); do { cin>>key; if (key=="0000") break; else { int max=wordNum-1,min=0; int result; result=BinarySearch(max,min,key); if (result==-1) cout<<"<------"<<"查无此词"<<endl; else cout<<"<------"<<word[result].word_class<<" "<<word [result].chinese<<endl; } cout<<endl; } while (1); return 0; } int BinarySearch(int max,int min,string key) { int median; while (min<=max) { median=(max+min)/2; if (word[median].english==key) { return median; } else if (word[median].english>key) max=median-1; else min=median+1; } return -1; }
运行结果:
学习心得:
在以前做过的电子词典的代码基础上改的,感觉好无奈啊,很多东西做过了都不记得怎么写,不知道程序员是不是一定要把代码牢牢记住啊,如果是,我就有点打退堂鼓了,上了大学之后发现自己还是花着高中一半的时间在搞学习,可效果收益只有高中的十分之一...唉唉。