第4章练习题--6--词典--2804

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Dic
{
    char el[11];
    char fl[11];
}Dic;
Dic dic[100001];
int q_cmp( const void *a ,const void *b)
{
    return  (strcmp( (*(Dic *)a).fl, (*(Dic *)b).fl));
}

int b_cmp( const void *a , const void *b)
{
    return  (strcmp( (char *)a, (*(Dic *)b).fl));
}

int main(int argc, char *argv[])
{
  Dic * p ;
  char doc[11],tmp[30];
  int i,k;
  
  k = 0 ;
  memset(dic, 0 , sizeof(Dic)*100001);
  memset(doc, 0 , sizeof(char)*11);
  while(1)
  {
         gets(tmp);
         if(tmp[0]=='\0')
             break;
         else 
         {
              sscanf(tmp, "%s%s",dic[k++].el , dic[k].fl);
              //sscanf(tmp, "%s%s",dic[k].el , dic[k++].fl);
              //出错原因在于:scanf、sscanf、printf都是右编译,从右往前执行的!! 
         }
  }
  
  qsort(dic, 100001, sizeof(dic[0]), q_cmp);
 
  while(scanf("%s",doc)!=EOF)
  {
      p = NULL ;
      p = (Dic *)bsearch(doc, dic, 100001 , sizeof(dic[0]), b_cmp);
      if(p)
      {
           printf("%s\n",p->el);
      }
      else printf("eh\n");
  }
  
  system("PAUSE");	
  return 0;
}

学习了一个新函数sscanf的用法,从字符串中读取字符串,但是该函数是右编译的,所以k++的操作要写在左边的数组中,否则就错了……这个错误好难发现,多谢达哥!

qsort和bsearch结合使用,注意比较函数的写法。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值