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]);
}

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.

Then the file doesn't exist where the program is looking for it.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.