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

In this C++ program we are counting the number of words, lines and the total size of a text file in bytes. I have used a text file “story.txt”. Make sure you already created this file and have some text in it. Place this file in the same directory where your source code file is present. I have used proper comments in the program to make it easy to understand. If you are still facing any problem then you can ask your questions in comment section.

Also Read: C++ Program to Count no. of alphabates, digits and spaces present in a file STORY.TXT

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

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

11 thoughts on “C++ Program to Count Number of Words, Lines and Total Size of a Text File”

  1. i was edit this program for counting average word size
    #include
    #include
    using namespace std;

    int main()
    {
    ifstream fin(“file.txt”); ///opening text file
    int line=1,word=1,size = 1; ///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 position for file pointer

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

    while(fin)
    {
    fin.get(ch);
    if(ch==’ ‘||ch==’\n’)
    word++;

    if(ch==’\n’)
    line++;
    }

    cout<<"Lines="<<line<<" "<<"nWords="<<word<<" "<<"nSize="<<(size/word)<<" "<<"n";
    fin.close(); //closing file

    return 0;

    }

  2. Sir
    I am new to programming. I am learning basics from your site. They really help me a lot. Could you please tell me what “story.txt” mean? Is it the file name? Should that particular file be open? can i do this with any file from my computer? does it require path directory?

  3. how about if you wanted to present in a column all the individual words and in the next column it displays the number of characters in each individual word?

  4. Hi,

    I want calculate only length text from line in file. Can you please me. Actually i have used strlen() but it calculating spaces from line.

Leave a Comment

Your email address will not be published. Required fields are marked *