码迷,mamicode.com
首页 > 其他好文 > 详细

第六章 结构

时间:2015-12-08 14:33:40      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

6.4 指向结构的指针

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAXWORD 100
//int binsearch(char *, struct key *, int);
#define NKEYS (sizeof keytab / sizeof(keytab[0]))
#define BUFSIZE 100
int getword(char *, int);
char buf[BUFSIZE];
int bufp = 0;

struct key {
    char *word;
    int count;
} keytab[] = {
    "auto", 0,
    "break", 0,
    "case", 0,
    "char", 0,
    "const", 0,
    "continue", 0,
    "default", 0,
    /* ... */
    "unsigned", 0,
    "void", 0,
    "volatile", 0,
    "while", 0
};
/* count C keywords */
main()
{
    int n;
    char word[MAXWORD];
    while (getword(word, MAXWORD) != EOF)
    if (isalpha(word[0]))
        if ((n = binsearch(word, keytab, NKEYS)) >= 0)
            keytab[n].count++;
        for (n = 0; n < NKEYS; n++)
            if (keytab[n].count > 0)
                printf("%4d %s\n", keytab[n].count, keytab[n].word);

    return 0;
}

/* binsearch: find word in tab[0]...tab[n-1] */

int binsearch(char *word, struct key tab[], int n)
{
    int cond;
    int low, high, mid;
    low = 0;
    high = n - 1;
    while (low <= high) {
        mid = (low+high) / 2;
        if ((cond = strcmp(word, tab[mid].word)) < 0)
            high = mid - 1;
        else if (cond > 0)
            low = mid + 1;
        else
            return mid;
    }
    return -1;
}

/* getword: get next word or character from input */

int getword(char *word, int lim)
{
    int c, getch(void);
    void ungetch(int);
    char *w = word;
    while (isspace(c = getch()))
        ;
    if (c != EOF)
        *w++ = c;
    if (!isalpha(c)) {
        *w = \0;
        return c;
    }
    for ( ; --lim > 0; w++)
        if (!isalnum(*w = getch())) {
            ungetch(*w);
            break;
    }
    *w = \0;
    return word[0];
}
int getch(void) /* get a (possibly pushed-back) character */
{
    return (bufp > 0) ? buf[--bufp] : getchar();
}
void ungetch(int c) /* push character back on input */
{
    if (bufp >= BUFSIZE)
        printf("ungetch: too many characters\n");
    else
        buf[bufp++] = c;
}
终端输出显示:
da
gfa
ray
allen
auto
void
los
static
register
break
ls
case
void
auto
break
continue
   2 auto
   2 break
   1 case
   1 continue
   2 void

 

第六章 结构

标签:

原文地址:http://www.cnblogs.com/try-again/p/5028928.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!