练习1-13:编写一个程序,打印输入中单词长度的直方图(水平)(C程序设计语言 第2版)

简单未考虑标点符号

#include <stdio.h>
#define MAX_WORD_LEN 10
#define BLANK 0
#define IN_WORD 1
#define START 2
main()
{
    int c, word_len, last_ch, i, j, len_array[MAX_WORD_LEN+1];

    for(i=0; i<MAX_WORD_LEN+1; i++){
        len_array[i] = 0;
    }

    i = 0;
    last_ch = START;

    while((c=getchar()) != EOF){
        if (c == ' ' || c == '\t' || c == '\n'){
                if (last_ch == IN_WORD){
                    if (i > MAX_WORD_LEN){
                        len_array[MAX_WORD_LEN]++;
                    }else{
                        len_array[i-1]++;
                    }
                    i = 0;
                }
                last_ch == BLANK;
        }else{
            last_ch = IN_WORD;
            i++;
        }
    }
    for (i=0; i<MAX_WORD_LEN+1; i++){
        if (i == MAX_WORD_LEN){
            printf(">10 ");
        }else{
            printf("%3d ", i+1);
        }
        j = len_array[i];
        while(j--){
            printf("-");
        }
        printf("\n");
    }
}
View Code

 

 

posted on 2013-09-18 17:17  Samuel Yang  阅读(417)  评论(0编辑  收藏  举报