Hi guys,
This program is supposed to count string length from the whole file, then count number of words and finally count average word length of all the words in file.
I seem to be having a problem with reading every line from a text file. So, the problem is that: it counts the words correctly, but length is being counted only from the first line of text file and it's being counted with every space and symbol.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define EIL 80
int main()
{
FILE *file;
char delim[] = " ,.!:;?\n";
char line[EIL];
char *words, *ptr;
int ch;
float length, word_count=0, words_average=0;
file = fopen ("file.txt", "r");
if (file==NULL)
printf ("\nError\n\n");
else
{
while ((ch=fgetc(file)) !=EOF)
{ fgets(line, EIL, file);
ptr = line;
if(words!=NULL)
{
length=0;
words=strtok(ptr, "");
length=strlen(words);
length++;
}
while ((words = strtok(ptr, delim)) !=NULL )
{
word_count++;
ptr = NULL;
}
}
words_average=length/word_count;
printf("Length: %.0f \nCount: %.0f \nAverage word length: %.2f\n\n", length, word_count, words_average);
fclose(file);
}
system("pause");
return 0;
}
Input file:
Code:
One ; Two Three : Four
Five Six!
Seven Eight
Any help would be appreciated, thanks.