Count lines, words and keywords in a text file | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Count lines, words and keywords in a text file

the exercise is to count the number of lines, words and keywords present in a text file. i was able to get the lines and the words counted, but i was unable to count the KEYWORDS present in the text file. there are 4 different keywords present in the text. could anyone help me with it. Thanks in advance. my code is: #include <stdio.h> int main() { FILE *fp; char filename[100]; char ch; int linecount, wordcount; linecount = 0; wordcount = 0; printf("Enter a filename :"); gets(filename); fp = fopen(filename,"r"); if ( fp ) { while ((ch=getc(fp)) != EOF) { if (ch == ' ' || ch == '\n') { ++wordcount; } if (ch == '\n') { ++linecount; } } if (wordcount > 0) { ++linecount; ++wordcount; } } else { printf("failed to open the file\n"); } printf("Lines : %d \n", linecount); printf("Words : %d \n", wordcount); return(0); }

31st Oct 2019, 10:30 PM
Earl
4 Answers
+ 6
No. Needs to be: #include <string.h> int match( char *word ) { char *targets[] = {"auto", "the", ""}; char **t = targets; while ( *t[0] != '\0' && strcmp(*t, word)) t++; return *t[0] != '\0'; }
2nd Nov 2019, 11:37 PM
John Wells
John Wells - avatar
+ 5
Store the letters between spaces into an array. Use strcmp to test match against each keyword. While this code can't run here, you can store it in the playground. Tag me in a comment on the code and I guide your coding.
1st Nov 2019, 3:38 AM
John Wells
John Wells - avatar
5th Nov 2019, 12:28 AM
Earl
0
will this work int match( char *word ) { char *targets[] = {"auto", "the"}; char *t = targets; while ( t && strcmp( t, word )) t++; return t != NULL;
2nd Nov 2019, 10:55 PM
Earl