/*
*Copyright(c)2014,烟台大学计算机学院
*All rights reserved.
*文件名称:test.cpp
*作者:满星辰
*完成日期:2014年 11月 29日
*版本号:v1.0
*
*问题描述:做一个简单的电子词典。
在文件dictionary.txt中,保存的是英汉对照的一个词典,词汇量近8000个,英文与释义间用’\t’隔开。
编程序,将文件中的内容读到两个数组e[]和c[]中,分别代表英文和中文,由用户输入英文词,显示中文意思。
运行程序后,支持用户连续地查词典,直到输入“0000”结束
*程序输入:
*程序输出:
*/
#include<iostream>
#include<fstream> //处理文件要包括头文件fstream
#include<cstdlib>
#include<string>
using namespace std;
int Tsearch(int low,int high,string word);
string words[8000];
string chinese[8000];
int main()
{
string word;
int i,n;
ifstream infile("dictionary.txt",ios::in);
//测试是否成功打开,打开失败时(如要读的数据文件不存在)退出
if(!infile)
{
cerr<<"open error!"<<endl;
exit(1);
}
for(i=0; i<8000; ++i)
{
infile>>words[i];
infile>>chinese[i];
if(words[i]=="")break;
}
infile.close(); //读入完毕要关闭文件
n=i;
do
{
cout<<"请输入要查询的词(0000结束本程序):";
cin>>word;
if(word=="0000")
break;
else
{
int low=0,high=n-1;
int index=Tsearch(low,high,word);
if(index==0)
cout<<"本词典未收录该词汇"<<endl<<endl;
else
cout<<words[index]<<'\t'<<chinese[index]<<endl<<endl;
}
}
while(word!="0000");
return 0;
}
int Tsearch(int low,int high,string word)
{
int mid;
while(low<=high)
{
mid=(low+high)/2;
if(words[mid]==word)
{
return mid;
}
if(words[mid]>word)
high=mid-1;
else
low=mid+1;
}
return 0;
}
运行结果:
学习心得:
做了好久,虽然一点也不长。。。主要是二分法不是很熟悉
度受上找了找二分法
似乎不是很难。。。。。