程序设计实训报告 项目3.2

#include <stdio.h>
#include<string.h>
#include<stdlib.h>

//定义词条类
typedef struct
{
    char english[20];
    char chinese[30];
    char word_class[10];
} Word;

Word words[8000];  //将词典数组设置成全局的结构体数组
int wordsNum=0;    //词典中的词条数目

/*从文件中将词读到字典中*/
void readDictionary()
{
    FILE *fp;
    //将文件中的数据读入到对象数组中
    fp = fopen("dictionary.txt","r");  //以输入的方式打开文件
    if(fp==NULL)       //测试是否成功打开
    {
        printf("dictionary open error!\n");
        exit(1);
    }
    while (!feof(fp))
    {
        fscanf(fp, "%s%s%s", words[wordsNum].english, words[wordsNum].chinese,words[wordsNum].word_class);
        ++wordsNum;
    }
    fclose(fp);
}

int BinSearch(int low, int high, char *key)
{
    int mid;
    while(low<=high)
    {
        mid=(low + high) / 2;
        if(strcmp(words[mid].english, key)==0)
        {
            return mid; //查找成功返回
        }
        if(strcmp(words[mid].english, key)>0)
            high=mid-1; //继续在w[low..mid-1]中查找
        else
            low=mid+1; //继续在w[mid+1..high]中查找
    }
    return -1; //当low>high时表示查找区间为空,查找失败
}

void searchWord(char *key)
{
    int low=0,high=wordsNum-1;  //置当前查找区间上、下界的初值
    int index=BinSearch(low, high, key);
    if(index>=0)
        printf("%s ---> %s \t %s", key, words[index].word_class, words[index].chinese);
    else
        printf("查无此词");
    printf("\n\n");
}

int main( )
{
    readDictionary();
    char key[20];
    do
    {
        printf("请输入待查询的关键词(英文),0000结束:\n");
        scanf("%s", key);
        if (strcmp(key,"0000"))
        {
            searchWord(key);
        }
        else
        {
            break;
        }
    }
    while(1);
    printf("欢迎再次使用!\n\n");
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值