问题描述:
做一个简单的电子词典。在文件dictionary.txt中,保存的是英汉对照的一个词典,词汇量近8000个,英文与释义间用’\t’隔开。编程序,将文件中的内容读到两个数组e[]和c[]中,分别代表英文和中文,由用户输入英文词,显示中文意思。运行程序后,支持用户连续地查词典,直到输入“0000”结束。提示:文件中的词汇已经排序,故在查找时,用二分查找法提高效率。
老师方案:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char e[8000][20],c[8000][20]; //英文和中文数组,要由文件中读入
int wordsNum=0; //词库中实际的词汇条数
int BinSeareh(int low, int high, char *k);
int main( )
{
char key[20]; //查询关键词
//将文件中的数据读入到对象数组中
FILE *fp;
fp = fopen("dictionary.txt","r"); //以输入的方式打开文件
if(fp==NULL) //测试是否成功打开
{
printf("open error!\n");
exit(1);
}
while(!feof(fp)) //读取成功,则重复从文件中读
{
fscanf(fp, "%s%s", e[wordsNum], c[wordsNum]);
++wordsNum;
}
fclose(fp);
//输入待查关键词并用二分查找法进行查询
do
{
printf("请输入要查的词(0000结束):");
scanf("%s", key);
if (strcmp(key,"0000")==0)
break;
else
{
int low=0,high=wordsNum-1; //置当前查找区间上、下界的初值
int index=BinSeareh(low, high, key);
if (index == -1)
printf("查无此词!\n\n");
else
printf("%s 的中文意思是:%s\n\n", key, c[index]);
}
}
while(1);
printf("欢迎再次使用!\n\n");
return 0;
}
//二分查找,结果为所查词在数组中的下标
int BinSeareh(int low, int high, char *k)
{
int mid;
while(low<=high)
{
mid=(low + high) / 2;
if(strcmp(e[mid],k)==0)
{
return mid; //查找成功返回
}
if(strcmp(e[mid],k)>0)
high=mid-1; //继续在e[low..mid-1]中查找
else
low=mid+1; //继续在e[mid+1..high]中查找
}
return -1; //当low>high时表示查找区间为空,查找失败
}
笔者方案:
#include "stdafx.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#pragma warning(disable:4996)
int main()
{
char english[8000][20] = {}, chinese[8000][40] = {};
FILE *fp;
fp = fopen("D:\\code\\dictionary.txt", "r");
if (fp == NULL)
{
printf("File cannot open! ");
exit(0);
}
char ch;
int count_word(0);
while (ch = getc(fp),ch != EOF)
{
if ('\t' == ch )
{
count_word++;
}
}
printf("本词典收入总词数:%d", count_word);
printf("\n");
fclose(fp);
fp = fopen("D:\\code\\dictionary.txt", "r");
int i(0), j(0),count(0);
char c;
while (count_word != count)
{
j = 0;
while (c=getc(fp),c!='\t')
{
english[i][j++] = c;
}
j = 0;
while (c = getc(fp), c!= '\n')
{
chinese[i][j++] = c;
}
i++;
count++;
}
fclose(fp);
char input[20] = {};
printf("请输入查询的词语(输入0000退出):");
gets_s(input);
while (strcmp(input, "0000")!=0)
{
if (0 == strcmp(input, english[0]))
{
printf("%s", chinese[0]);
}
else if (0 == strcmp(input, english[count_word-1]))
{
printf("%s", chinese[count_word-1]);
}
else
{
char med[20] = {};
int head(0), end(count_word - 1), goal(-1);
while ((end - head) != 1)
{
strcpy(med, english[(head + end) / 2]);
if (strcmp(input,med)>0)
{
head = (head + end) / 2;
}
else if (strcmp(input, med)<0)
{
end = (head + end) / 2;
}
else if (strcmp(input, med) == 0)
{
goal = (head + end) / 2;
break;
}
}
if (goal > 0)
{
printf("%s", chinese[goal]);
}
else
{
printf("词典未收录该词");
}
}
printf("\n"); printf("\n");
printf("请输入查询的词语(输入0000退出):");
gets_s(input);
}
return 0;
}
效果图: