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

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

    Reply
  2. arindam sarkar

    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;

    }

    Reply
  3. new programmer

    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?

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

      Reply
  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?

    Reply

Leave a Reply

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