电子词典
做一个简单的电子词典。在文件dictionary.txt中,保存的是英汉对照的一个词典,词汇量近8000个,英文与释义间用’\t’隔开。编程序,将文件中的内容读到两个数组e[]和c[]中,分别代表英文和中文,由用户输入英文词,显示中文意思。运行程序后,支持用户连续地查词典,直到输入“0000”结束,如图:
提示:文件中的词汇已经排序,故在查找时,用二分查找法提高效率。
如下:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int w=0;
char e[9999][999],c[9999][999]; //用两个数组从文件中读入英文和汉译
int Binary_Seareh(char p[999]);
int main()
{
int i,n,m,j,k,t;
int flag; //标记大小写
char s[99],ss[99];
printf("##############################\n");
printf("\n");
printf("--Welcome_to_SuperDictionary--\n"); //欢迎界面
printf("\n");
printf("##############################\n");
FILE *fp;
fp=fopen("dictionary.txt","r");//打开文件
if(fp==NULL)
{
printf("Please check the file situction."); //文件打开问题处理
exit(0);
}
else
{
while(!feof(fp))
{
fscanf(fp,"%s%s",e[w],c[w]); //把数据读入到数组里保存
w++;
}
fclose(fp);
}
printf("\n");
printf("If you want to quit please input 0000\n");
printf("\n");
while(1)
{
flag=1;
printf("<<Please input the word that you want to konw>>\n");
printf("\n");
gets(s);//输入要查找的单词
int x=0,m=-1;
while(s[x]!='\0')
{
if(s[x]!=' '&&m!=-1)
{
s[m]=s[x];
m++;
}
else if(s[x]==' '&&m==-1)//删除空格
{
m=x;
}
x++;
}
if(m!=-1)
{
s[m]='\0';
}
t=strlen(s);
for(i=0;i<t;i++)
{
if(s[i]>='A'&&s[i]<='Z') //大写转小写
{
s[i]+=32;
flag=0;
}
}
if(strcmp(s,"0000")==0) //退出判断
{
break;
}
else
{
i=Binary_Seareh(s); //二分查找目标单词
if(i==0)
{
printf("Sorry,I can't find this word and please input another word.\n");
printf("\n");
}
else
{
if(flag==0)
{
printf("\n");
printf("The word maybe is '%s' : %s",s,c[i]);
printf("\n"); //输入大写时转换成小写输出提示信息
}
else
{
printf("\n");
printf(" '%s' is %s\n",s,c[i]);
printf("\n"); //输入正常
}
printf("\n");
}
}
}
printf("See you again!\n");
}
/*************************************************************
功能描述;对输入进来的单词进行二分查找。
输入参数:P 要查找的单词
返 回 值:0
其他说明:无
*************************************************************/
int Binary_Seareh(char p[999])
{
int low=0,mid,high=w-1;
while(low<=high)
{
mid=(low+high)/2;
if(strcmp(e[mid],p)==0) //利用strcmp函数对输入进来的单词与文件中单词比对
{
return mid;
}
if(strcmp(e[mid],p)>0)
{
high=mid-1;
}
else
{
low=mid+1;
}
}
return 0;
}