Start New Discussion within our Software Development Community

guyss i just want to ask if anyone could show me a sample program on how to count the number of words,letters,and sentences in a file....using the c language....

thanks in advance!!

Start out very simple by counting the number of letters in a sentence. When you get that finished and tested then you can write the code to count the number of words. Do just one part of it at a time so that you don't get overwhelmed by the complexity. You will need integers to contain the counts and a loop to inspect each character of the string.

Write the code to count letters, then post what you have written and feel free to ask specific questions about what you don't understand.

# include <stdio.h>
# include <string.h>
# include <ctype.h>
int static words = 0,chars = 0,senten = 0;
int i = 0;

main()/*start of main function*/
	char ch;
	char ch1[1000];
	fp1 = fopen("NUMBERofCHars.txt","w");
	fp = fopen("Paragraph.txt","r+");
	while((ch=fgetc(fp)) != EOF) {
		ch1[i] = ch;
      	if (ch1[i] == '.'){/*condition for number of sentences*/
		senten = senten + 1;
	if (ch1[i] != ' '){/*Condition for number of letters*/
		chars = chars + 1;
	if (ch1[i] == ' '){/*condition for number of words*/
		words  = words + 1;
	fprintf(fp1,"Number of words : %d\n",words);
	fprintf(fp1,"Number of letters: %d\n",chars);
	fprintf(fp1,"Number of sentence: %d\n",senten);
	fclose(fp);	fclose(fp1);
}/*End of main*/

here is my code..

i get an on error when i run the program it does not give the exact number of words letters and sentence....i don't know where i had a mistake on my code..

Gee, I wonder what you types in. I also wonder what answers you got.

Any help is dependent on the input and output.

You don't need that chr1 declared on line 10. Why save the input characters? Just read a character from the file and process it.

line 17: sentences also end in ? and ! characters.

line 20: you need to increment the number of characters count for each character read in from the file, not just the number of spaces. Delete lines 20 and 22, leaving only chars = chars + 1.

This article has been dead for over six months. Start a new discussion instead.