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

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. Daljeet

    What’s the use of line no. 12,15,19??? U are simply putting the pointer to beg. Only..

  2. arindam sarkar

    i was edit this program for counting average word size
    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

    if(ch==’ ‘||ch==’\n’)


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

    return 0;


  3. new programmer

    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?

    1. Admin Post author

      You can use any file. If the source code file and text file are in the same directory then no need to provide path.

  4. new programer

    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?

  5. reet

    what if there are multiple spaces between 2 words ??????????????????????????????

  6. Khasim


    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.

  7. kiran

    i want to calculate length of each line in the text file could u plz help me


Leave a Reply

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