-
String Counter
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:
Code:
#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]);
}
-
So does it work for you at the moment?
It certainly seems to output the count of the number of words of each length.
-
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.
-
> fpt=fopen(fname, "r");
> if ((fpt=fopen(argv[1],"r")) == NULL)
Why are you opening it twice?
With two different names?
Probably, your argv is empty, and the 2nd one fails.