c-如何生成具有相同字符数的单词数



我正在学习k&r和我遇到了这个练习"写一个程序来打印输入中单词长度的直方图。画水平条形的直方图很容易;垂直方向更具挑战性",我决定对这个问题做一点修改,所以这就是我目前所得到的:

 #include <stdio.h>
    #define OUT 0
    #define IN 1
    main(){
        int c, nw, nc, i,state,j;
        nw = nc = 0;
        while ((c = getchar()) != EOF){
            if (c == 'n' || c == 't' || c == ' ')
                state = OUT;
            else if (state == OUT) {
                state = IN;
                ++nw;
            }

    if (state == IN) {
                    if (c >= 'a' && c <= 'z')
    ++nc;
    if ( c >='0' && c<='9')
    ++nc;
            }
        }
        printf("Lengths of words");
        for (j = 1; j < 10; ++j){
                printf("[%d]-%d", j, nw);
        }
     }

这就是我期望计算机打印出来的:

 Lengths of words
    [0]- nw with > 10 characters
    [1]- nw with 1 character
    [2]- nw with 2 characters
    [3]- nw with 3 characters
    ...

例如:my name is linh,这就是它将打印的内容:

[0]- 0
[1]- 0
[2]- 2
[3]- 0
[4]- 0
...

我知道这个练习是关于数组的,因此,我可能在这个程序中遗漏了它的概念,需要有人纠正我的错误:)我很想知道如何生成具有相同字符数的单词数。此外,我希望我的代码以某种方式被审查。。。我相信这里面有一些误解。我对C比较陌生,如果你能给我任何帮助,我将不胜感激:)提前谢谢!

我试图解决你的问题。我希望它能帮助你,它足够简单,对你来说很清楚。

 #include <stdio.h>
typedef int bool;
#define true 1
#define false 0
#define maxNumOfWords 10
char *createHistogram(int n) {
    char *hist = (char *)malloc((n + 1) * sizeof(char));
    if (hist == NULL) {
        return "";
    }
    int i = 0;
    for (i = 0; i < n; i++) {
        hist[i] = '*';
    }
    hist[i] = '';
    return hist;
}
int main(int argc, char *argv[]) {
    bool isInWord = false;
    int results[maxNumOfWords];
    int index = -1;
    int j;
    char c;
    // initialize the result array to 0
    for (j = 0; j < maxNumOfWords; j++) {
        results[j] = 0;
    }
    while ((index < maxNumOfWords) && ((c = getchar()) != EOF)) {
        switch (c) {
        case 'n':
        case 'r':
        case 't':
        case ' ':
            isInWord = false;
            break;
        default:
            // on the beginning of the first word
            if (isInWord == false) {
                ++index;
            }
            isInWord = true;
            if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))
                results[index] += 1;
            break;
        }
    }
    printf("Lengths of words:n");
    for (j = 0; j < maxNumOfWords; j++) {
        int n = results[j];
        printf("[%d]-%d %sn", j, n, createHistogram(n));
    }
}

最新更新