I have to write a program for an assignment to scan a text file and say how many sentences there are (based on number of full stops, no other punctuation) the number of words in total and the total number of times a certain word appears. I can get the count of total words working but the specific word count and sentence count elude me, I believe we are meant to use fscanf
. Here is what I have
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
FILE *datafile;
int main(){
int count1, count2, leng, sentences ;
char filename[50], word[120], sentence[120];
printf("Enter a word :");
gets(word);
printf("Enter the filename:");
gets(filename);
datafile = fopen(filename, "r");
if(datafile == NULL) {
printf("Error , Can not open %s", filename);
exit(249);
}
leng = 0;
count2 = 0;
sentences = 0;
while (fscanf(datafile, "%s", word) == 1) { //this one works
++leng;
}
while (!feof(datafile))
{
fscanf(datafile,"%s",word);
if (strcmp(word,"the")==0)
count2++;
}
while(fscanf(datafile, "%s", word) == '.') {
++sentences;
}
printf("There are a total of %d words\n", leng);
printf("The word '%s' appears %d times\n", word, count2);
printf("There are %d sentences", sentences);
}
when I run it this is what I get
I tried two different ways for the sentence count and specific word count and i dont really understand why the first one works either , I imagine once I have one of them the other will be the same format . Any help or advice is appreciated.