Chinaunix首页 | 论坛 | 博客
  • 博客访问: 221004
  • 博文数量: 136
  • 博客积分: 2919
  • 博客等级: 少校
  • 技术积分: 1299
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-11 09:08
文章分类

全部博文(136)

文章存档

2013年(1)

2011年(135)

我的朋友

分类: C/C++

2011-03-27 10:16:37

  1. /* k&r(6.4): Pointers to Structures
  2.    created on Mar 27, 2011
  3.    */

  4. #include "stdio.h"
  5. #include "ctype.h"
  6. #include "string.h"
  7. #define MAXWORD 100

  8. #define NKEYS (sizeof keytab / sizeof keytab[0])

  9. struct key {
  10.     char *word;
  11.     int count;
  12. } keytab[] = {
  13.     "auto", 0,
  14.     "break", 0,
  15.     "case", 0,
  16.     /* ...*/
  17.     "while", 0
  18. };

  19. int getword(char *, int);
  20. struct key *binsearch(char *, struct key *, int);

  21. /* count C keywords; pointer version */
  22. int main()
  23. {
  24.     char word[MAXWORD];
  25.     struct key *p;

  26.     while (getword(word, MAXWORD) != EOF)
  27.      if (isalpha(word[0]))
  28.         if ((p = binsearch(word, keytab, NKEYS)) != NULL)
  29.          p->count++;
  30.     for (p = keytab; p < keytab + NKEYS; p++)
  31.      if (p->count > 0)
  32.         printf ("%4d %s\n", p->count, p->word);
  33.     return 0;
  34. }

  35. /* binsearch: find word in tab[0]...tab[n-1] */
  36. struct key *binsearch(char *word, struct key *tab, int n)
  37. {
  38.     int cond;
  39.     struct key *low = &tab[0];
  40.     struct key *high = &tab[n];
  41.     struct key *mid ;

  42.     while (low < high) {
  43.         mid = low + (high-low)/2;
  44.         if ((cond = strcmp(word, mid->word)) < 0)
  45.          high = mid;
  46.         else if (cond > 0)
  47.          low = mid + 1;
  48.         else
  49.          return mid;
  50.     }
  51.     return NULL;
  52. }

  53.  /* getword: get next word or character from input */
  54. int getword(char *word, int lim)
  55. {
  56.     int c, getch(void);
  57.     void ungetch(int);
  58.     char *w = word;

  59.     while (isspace(c = getch())) //not getchar() here
  60.      ;
  61.     if (c != EOF)
  62.      *w++ = c;
  63.     if (!isalpha(c)) {
  64.         *w = '\0';
  65.         return c;
  66.     }
  67.     for (; --lim > 0; w++)
  68.      if (!isalnum(*w = getch())) {
  69.          ungetch(*w);
  70.          break;
  71.      }
  72.     *w = '\0';
  73.     return word[0];
  74. }
阅读(426) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~