电子词典

C++字典查找与文件操作实现
#include <fstream>  
#include <iostream>  
#include <string>  
#include <cstdlib>   //调用exit(1)需要包含cstdlib  
using namespace std;  
int Middle (string,int,int);  
const int num=8100;  
string Chinese[num],English[num];  
int main()  
{  
    int i,get,a=0,left=0,right=8099;  
    string word;  
    ifstream infile("dictionary.txt",ios::in);    //测试是否成功打开,打开失败时(如要读的数据文件不存在)退出  
    if(!infile)  
    {  
        cerr<<"open error!"<<endl;  
        exit(1);  
    }  
    for(i=0; i<num; i++)  
    {  
        infile>>English[i]>>Chinese[i];  
        a++;  
    }  
    infile.close();  
    while(word!="0000")  
    {  
        cout<<"请输入一个英文单词: ";  
        cin>>word;  
        get=Middle(word,left,right);  
        if(get!=-1)  
            cout<<English[get]<<"\t"<<Chinese[get]<<endl<<endl;  
        else  
        {  
            cout<<"该词典中没有这个单词!\n";  
            break;  
        }  
    }  
    return 0;  
}  
  
int Middle (string word,int left,int right)  
{  
  
    while(left<=right)  
    {  
        int half=(left+right)/2;  
        if(English[half]==word)  
        {  
            return half;  
        }  
        else if(English[half]>word)  
        {  
            right=half-1;  
        }  
        else  
        {  
            left=half+1;  
        }  
  
    }  
    return -1;  
}  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值