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

How can i generate the number of words with the same number of characters?

我正在通过 k&r 学习 c 编程语言,我遇到了这个练习 "Write a program to print a histogram of the lengths of words in its input. It is easy to draw the histogram with the bars horizontal; a vertical orientation is more challenging"我决定对这个问题做一些修改,这就是我到目前为止所得到的:

 #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] = '[=10=]';
    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 %s\n", j, n, createHistogram(n));
    }
}