第17周项目7-电子词典结构体版

本文介绍了一个基于C++的简易电子词典程序,详细阐述了如何读取和存储词汇,以及提供高效的搜索功能。程序通过结构体封装词汇信息,并使用二分查找算法进行快速检索。

问题及代码:

/*
 *Copyright(c)2014,烟台大学计算机学院
 *Allrights reserved.
 *文件名称:MADE88.cpp
 *作    者:孙化龙
 *完成日期:2014年12月23日
 *版 本 号:v1.0
 *
 *问题描述:做一个简单的电子词典
*/
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cstring>
using namespace std;
struct Word
{
    string english;
    string chinese;
    string wordclass;
};

int main()
{


    Word words[8000];
    int i,wordsNum=0;
    ifstream infile("dictionary.txt",ios::in); 	//以输入的方式打开文件
    if(!infile)   				//测试是否成功打开
    {
        cerr<<"open error!"<<endl;
        exit(1);
    }
    i=0;
    while(infile>>words[i].english>>words[i].chinese>>words[i].wordclass)
    {
        ++wordsNum;
        ++i;
    }
    infile.close();
    string key="a";

      while(key!="0000")
        {
        cout<<"输入要查找的词(0000退出):";
        cin>>key;

        int low=0,high=wordsNum-1,mid;

        while(low<=high)
        {
            mid=(low+high)/2;
            if(words[mid].english==key)
            {
                cout<<words[mid].english<<"<---"<<words[mid].wordclass<<words[mid].chinese<<endl;
                break;
            }
            else if(words[mid].english>key)
                high=mid-1;
            else if(words[mid].english<key)
                low=mid+1;
        }
        if(low>high&&key!="0000")
            cout<<"查无此词"<<endl;
        }



    return 0;
}


运行结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值