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

Q. 5 Consider the problem of counting the number of words in a text file that ma

ID: 3676013 • Letter: Q

Question

Q. 5 Consider the problem of counting the number of words in a text file that may contain letters plus any of the following characters: <blank> <linefeed> <end-of-file> , . ; : ? !

Define a word to be a string of letters that is preceded by either the beginning of the file or some non-letter character and that is followed by some non-letter character. For example, there are 11 words in the following text:

The <blank> <blank> cat <blank> <linefeed>

saw <blank> the <blank> <blank> <blank> rat <linefeed>

<blank> with

<linefeed> a <blank> hat <linefeed>

on <blank> the <blank> <blank> mat <end-of-file>

Describe a very simple finite-state machine that reads the characters in the file one at a time and solves the word-counting problem. Assume that there exists an output symbol with the property that, every time it is generated, an external counter gets incremented. (Hint: Take input symbols L (for letter), N (for a nonletter) and E (for end-of-file). The output symbol A (for add one to the counter)..

Explanation / Answer

#include<iostream.h>

#include<fstream.h>

int main()

{

ifstream fin("story.txt"); //opening text file

int line=1,word=1,size; //will not count first word and last line so initial value is 1

char ch;

fin.seekg(0,ios::end); //bring file pointer position to end of file

size=fin.tellg(); //count number of bytes till current postion for file pointer

fin.seekg(0,ios::beg); //bring position of file pointer to begining of file

while(fin)

{

fin.get(ch);

if(ch==' '||ch=='n')

word++;

  if(ch=='n')

line++;

}

cout<<"Lines="<<line<<"nWords="<<word<<"nSize="<<size<<"n";

fin.close(); //closing file

return 0;

}