第十四周项目4-电子词典(数据由dictionary.txt提供)

/*
 *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;
}

运行结果:

学习心得:

做了好久,虽然一点也不长。。。主要是二分法不是很熟悉

度受上找了找二分法

似乎不是很难。。。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值