开发一个电子词典(下载词库点击打开链接)
#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; }