Print the lengths of words

I am trying to do Exercise 1-13 from The C Programming Language book which is: 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.

Right now I am just trying to print how many times a certain length appears and worrying about the histograms later.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <stdio.h>

main() {
    int MAXLENG = 10; //the maximum length for a word is 10, words longer than 10 will be shown as >10 on the histogram
    int c; //will hold the value of each character entered
    int x; //used for for loop to print output
    int wordlengs[MAXLENG];
    int leng; //the length of a word
    leng = 0;

    while((c = getchar()) != EOF) {
        if(c != ' ') { //if c isn't a space then keep counting the characters as part of a word
            leng++;
        } else { //if c is a space then stop counting the length of the word
            if(leng > MAXLENG) { //depending on the value of `leng' create a `tally' in wordlengs[]
                wordlengs[0]++;      //1 letter `words' go to wordlengs[1], 2 leng words => wordlengs[2] etc... 10 leng words => wordlengs[10] so or words over 10 would go to wordlengs[0]
                leng = 0; //after the length of one word has been added to the tally, the length of the next word needs to start at 0
            } else {
                wordlengs[leng]++;
                leng = 0;
            }
        }
    }

    for(x = 1; x <= MAXLENG; x++) {
        printf("%d, %d letter words\n",wordlengs[x], x);
    }
    printf("%d, >10 letter words\n", wordlengs[0]);
}


It compiles fine but doesn't seem to output anything, even if I just add something like `printf("hello");' as the last line.

Could someone tell me what I am doing wrong and also if this is the right way to go about counting the lengths of words entered?
Last edited on
@LSD

Line 16 has a problem with the subscript - the comment tells what needs to happen, but the code doesn't reflect that.
Line 25 this will miss the first one, and cause a seg fault on the last one

Also, you are not printing a histogram with *'s.

The reason it doesn't do anything, is you haven't input anything from a file. Some of the programs in K&R rely on input being piped into your program in the UNIX / Linux shell, as in :

cat MyDataFile | Myprogram.


I am not sure whether it is possible to do this on windows.

If you don't have Linux, then you might have to actually read from a file.



Hope all goes well.
Last edited on
Topic archived. No new replies allowed.