Search code examples
cgetchar

C program to count number of n-letter words in a text stuck in nested while loop


I'm getting back into coding after quite a few years out of school and I'm stuck trying to write a program in C that counts how many n-letter words are in a text, storing them into a length n array and then printing them. To keep is simple, I've assumed n is b/w 1 and 10 and each word is seperated by exactly one space.

Here's the code, However, it seems my program never gets out of the inner while loop so nothing is printed on the screen. I tried printing something at the end of that loop to test it and for some reason the program prints it as many times as there are characters (including spaces, which the inner while condition should catch and exit). Am I overlooking something here?

main()
{
int c, i, j, counter;
counter = 0;
int wlength [10];
for (i=0; i<10; ++i) //initialize array
    wlength[i]=0;
while((c=getchar())!=EOF){ // keep taking input until end of file
    while (c!=' '){   //keep counting until you reach the end of the word
        ++counter;
        c=getchar(); 
    }
    wlength [counter-1]++;  //increment the counter for that word length
    counter=0 ; //reset the counter for the next word
}
for (j=0;j<10;++j) //print the array
    printf("%d ", wlength[j]);

Solution

  • You have two loops reading standard input, and only one checks for EOF. So your program reads the file and gets stuck if there isn't exactly a space before the end of the file. You would be better off with only one loop, replacing the other by an if - else statement :

    Pseudo-code :
    while ( getchar  and !EOF )
    {
        if ( char isn't a space )
        {
            increment counter
        } else {
            increment value for given length
            set first counter to 0
        }
    }
    

    You should also check that you're in the bounds of your array... Words like 'expotentially` exist ;-)