Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a C program that finds the number of words and sentences in a given txt fi

ID: 3826742 • Letter: W

Question

 Write a C program that finds the number of words and sentences in a given txt file. ( A sample essay is provided for testing).  This is the essay in the .txt file:  Faces are essential to expressing emotion, consciously or unconsciously.  A frown denotes disapproval; a smile usually means someone is pleased. Being able to read emotion in another's  face is "the fundamental basis for empathy and the ability to interpret a person’s reactions and predict the  probability of ensuing behaviors". One study used the Multimodal Emotion Recognition Test[5] to attempt to  determine how to measure emotion. This research aimed at using a measuring device to accomplish what people  do so easily everyday: read emotion in a face. 

Explanation / Answer

#include <stdio.h>

int main()
{
FILE *fp;
char filename[100];
char ch;
int linecount, wordcount, charcount;

// Initialize counter variables
linecount = 0;
wordcount = 0;

// charcount is maintained for last line
charcount = 0;

// Prompt user to enter filename
printf("Enter a filename :");
scanf("%s", &filename);
  
// Open file in read-only mode
fp = fopen(filename,"r");

// If file opened successfully, then write the string to file
if ( fp )
{
   //Repeat until End Of File character is reached.
   char prevChar='';
   while ((ch=getc(fp)) != EOF) {
      // Increment character count if NOT new line or space
       if (ch != ' ' && ch != ' ') { ++charcount; }
      
       // Increment word count if new line or space character
       if ((ch == ' ' && prevChar != ' ') || (ch == ' ' && prevChar != ' ')) { ++wordcount; }
         
       // Increment line count if new line character
       if (ch == ' ') { ++linecount; }
         
prevChar = ch;

   }

   if (charcount > 0) {
       ++linecount;
       ++wordcount;
   }
}
else
{
printf("Failed to open the file ");
}

printf("Lines : %d ", linecount);
printf("Words : %d ", wordcount);
return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote