单词计数 hello

The C Program Language 6.5节

统计所用输入单词出现的次数,为啥遍历会出现错误

  1 #include<stdio.h>
  2 #include<ctype.h>
  3 #include<string.h>
  4 #include<stdlib.h>
  5 
  6 #define MAXWORD 100
  7 struct tnode{
  8     char *word;
  9     int count;
 10     struct tnode *left;
 11     struct tnode *right;
 12 };
 13 
 14 struct tnode *addtree(struct tnode*, char *);
 15 void treeprint(struct tnode*);
 16 int getword(char *, int);
 17 
 18 int main()
 19 {
 20     struct tnode *root;
 21     char word[MAXWORD];  
 22     root = NULL;
 23     while(getword(word, MAXWORD) != EOF)
 24         if(isalpha(word[0]))
 25             root = addtree(root, word);
 26     treeprint(root);
 27    // printf("%d\n", num);
 28     getchar(); 
 29     return 0;
 30 }
 31 
 32 struct tnode *talloc()
 33 {
 34     return (struct tnode *)malloc(sizeof(struct tnode));
 35 }
 36  
 37 struct tnode* addtree(struct tnode *p, char *w)
 38 {
 39     int cond;
 40     if(p == NULL)
 41     {
 42         p = talloc();
 43         p->word = strdup(w);
 44         p->count = 1;
 45         p->left = p->right = NULL;
 46     }
 47     else if((cond=strcmp(w, p->word)) == 0)
 48         p->count++;
 49     else if(cond < 0)
 50         p->left = addtree(p->left, w);
 51     else
 52         p->right = addtree(p->right, w);   
 53     return p;
 54 }
 55 
 56 void treeprint(struct tnode *p)
 57 {
 58     if(p != NULL)
 59     {
 60         treeprint(p->left);
 61         printf("%s %4d\n", p->count, p->word);
 62         //num++;
 63         treeprint(p->right);
 64     }      
 65 }
 66 
 67 #define BUFFSIZE 100
 68 char buf[BUFFSIZE];
 69 int bufp = 0;
 70 int getch()
 71 {
 72     return bufp>0 ? buf[--bufp] : getchar();
 73 }
 74 
 75 void ungetch(int c)
 76 {
 77     if(bufp > BUFFSIZE)
 78         printf("ungetch: too many characters\n");
 79     else
 80         buf[bufp++] = c;
 81 }
 82 
 83 int getword(char *word, int lim)
 84 {
 85     int c;
 86     char *w = word;
 87     while(isspace(c = getch()))
 88         ;
 89     if(c != EOF)
 90         *w++ = c;
 91     if(!isalpha(c))
 92     {
 93         *w = '\0';
 94         return c;
 95     }
 96     for(; --lim>0; w++)
 97         if(!isalnum(*w = getch()))
 98         {
 99             ungetch(*w);
100             break;
101         }
102     *w = '\0';
103     return word[0];
104 }
原文地址:https://www.cnblogs.com/fightever/p/3818317.html