C++ Program to Count Number of Words, Lines and Total Size of a Text File

In this C++ program, we are tallying the number of words, lines and the all-out size of a book record in bytes. I have utilized a content document “story.txt”.

Ensure you previously made this document and have some content in it. Spot this record in a similar index where your source code document is available.

Program

#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;
 
}

Output

C++ Program to Count Number of Words, Lines and Total Size of a Text File

I have utilized appropriate comments in the program to make it straightforward. On the off chance that you are as yet confronting any

issue, at that point, you can pose your inquiries in the comment area.

Leave a Comment

error: Alert: Content is protected!!