C語言練習-字符串二維數組

查字典

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define SIZE 10000
char eng[SIZE][26],chn[SIZE][26],ch[26];            //定義全局變量,別的函數可以直接用
int BinSearch(int low,int high,char key[]);
int main()
{

    FILE *fp;
    int i=0;
    if((fp=fopen("dictionary.txt","r"))==NULL)
    {
        printf("Can not open the file.\n");
        exit(0);
    }
    while((fscanf(fp,"%s%s",eng[i],chn[i])!= EOF))
    {
        i++;
    }
    fclose(fp);
    do
    {
        printf("enter the English word(0000 to quit): ");
        scanf("%s",ch);
        if(strcmp(ch,"0000")==0)
            break;
        else
        {
            int low=0,high=i-1;
            int index = BinSearch(low,high,ch);
            if(index==-1)
                printf("No such word!");
            else
                printf("%s meaning is : %s\n\n",ch,chn[index]);
        }
    }
    while(1);
    return 0;
}

int BinSearch(int low,int high,char key[])
{
    int mid;
    while(low<=high)
    {
        mid=(low+high)/2;
        if(strcmp(eng[mid],key)==0)
            return mid;
        if(strcmp(eng[mid],key)>0)
            high = mid-1;
        else
            low = mid+1;
    }
    return -1;

}

猜你喜欢

转载自blog.csdn.net/weixin_38486169/article/details/86614648