问题描述:
做一个简单的电子词典。在文件 dictionary.txt中,保存的是英汉对照的一个词典,词汇量近 8000个,英文与释义间用’\t’隔开。编程序,将文件中的内容读到两个数组 e[]和 c[]中,分别代表英文和中文,由用户输入英文词,显示中文意思。运行程序后,支持用户连续地查词典,直到输入“0000”结
束。
代码:
#include <iostream>
#include <string>
#include <cstdlib>
#include <fstream>
const int n=8000;
using namespace std;
int main()
{
int i,low,high,mid,index;
string chianese[n],english[n],key;
ifstream infile ("dictionary.txt",ios::in);
if(!infile)
{
cout<<"open error!"<<'\n';
exit(1);
}
i=0;
while(infile>>english[i]>>chianese[i])
i++;
infile.close();
cout<<" 欢迎使用星耀电子词典"<<'\n';
do
{
cout<<"请您输入想要查询的单词(输入0000结束):";
cin>>key;
low=0,high=n-1,index=-1;
while(low<=high)
{
mid=(low+high)/2;
if(english[mid]==key)
{
index=mid;
break;
}
else if(english[mid]>key)
high=mid-1;
else
low=mid+1;
}
if(index >= 0)
{
cout<<english[index]<<"的中文意思是:"<<'\t'<<chianese[index]<<'\n';
cout<<'\n';
}
else
{
cout<<"经星耀词典鉴定,查无此词!"<<'\n';
cout<<'\n';
}
}
while (key!="0000");
cout<<"感谢您的使用,愿您生活快乐,工作顺利!!!";
return 0;
}
运行结果: