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

全部博文(136)

文章存档

2013年(1)

2011年(135)

我的朋友

分类: C/C++

2011-03-27 09:45:10

  1. /* k&r(6.3): Arrays of 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. int binsearch(char *, struct key *, int);

  21. /* count C keywords */
  22. int main()
  23. {
  24.     int n;
  25.     char word[MAXWORD];

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

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

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

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

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