I am trying to make a program that will read in a text file and count the number of words that have a certain length from 1 to 20. So it should count the words that have a length of one, two, etc., and print it out. I have been working on this for some time, and have taken pointers from some people and have destroyed and rebuilded my code several times. Any help on how I can go about programming this, would be appreciated it.

This is where my code is at right now:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])

{
        FILE *fpt;
        int count[20],i,s;
        char word[80];
        char fname[128];

        printf("Enter filename: ");
        scanf("%s",fname);
        fpt=fopen(fname, "r");

        if ((fpt=fopen(argv[1],"r")) == NULL)
        {
                printf("Unable to open %s for reading\n",argv[1]);
                exit(0);
        }
        for (i=0; i<20; i++)
                count[i]=0;
        while (fscanf(fpt,"%s",word) == 1)
        {
                s=strlen(word);
                if (s >= 3 && s <= 15)
                        count[s]++;
        }
        for (i=3; i<=15; i++)
                if (count[i] > 0)
                printf("Words of length %d: %d\n",i,count[i]);
}

Edited 5 Years Ago by WaltP: Fixed CODE Tags -- you ARE allowed to edit your post to correct misakes like this.

I am trying to make a program that will read in a text file and count the number of words that have a certain length from 1 to 20. So it should count the words that have a length of one, two, etc., and print it out. I have been working on this for some time, and have taken pointers from some people and have destroyed and rebuilded my code several times. Any help on how I can go about programming this, would be appreciated it.

When asking for help, you need to tell us what the problem is. Don't leave it to us to figure it out.

For some reason it is not taking in the text file when it propmpts for it, it just ends program. Also I'm not sure if it will count the words of certain length.

At line 10 you open a file as prompted. At line 16 you immediately discard the result and open another file, which name is given as a command line argument. Which one do you really want?

PS: if the command line has no arguments, the result is pretty much undefined.

This article has been dead for over six months. Start a new discussion instead.