Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
my task 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.


What I have tried:

#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);
}
Posted
Updated 1-Nov-19 8:42am

 
Share this answer
 
Quote:
but i was unable to count the KEYWORDS present in the text file

The problem here is that you didn't try to do the count.

Try to read this as a file and see how many words it find:
First

     Second-third
 Fourth    fifth

There is a surprise. :)

Advice: Learn to indent properly your code, it show its structure and it helps reading and understanding. It also helps spotting structures mistakes.
C++
#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);
}

Indentation style - Wikipedia[^]

Professional programmer's editors have this feature and others ones such as parenthesis matching and syntax highlighting.
Notepad++ Home[^]
ultraedit[^]
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900