codescracker
c++

C++ Program to Count Characters, Words, Lines in a File



« C++ Tutorial C++ Example »

This article provides some programs in C++ that count and prints total number of characters, words, lines, vowels etc. in a file. The name of file must be entered by user at run-time. This article deals with these programs:

What to do Before Program ?

Since the program given below operates on a file. Therefore a file must be available/created inside the current directory (the folder where the C++ program's source code is saved). Because I've not created a file, so let me create a file say codescracker.txt. Here is the snapshot of the folder where this file is created and saved right now:

c++ count number of characters in file

Now put some content inside this file, so that the program given below counts all the things like characters, words, lines, vowels, consonants, blank spaces etc. available in the file. Here is the snapshot of the opened file, codescracker.txt after writing/putting some content:

c++ count number of words in file

Now let's move on and create a program in C++ that counts characters, words, and lines etc. from this file using the program.

Count Number of Characters in a File

The question is, write a program in C++ that receives the name of file from user at run-time to count and print the total number of characters available in the file. The answer to this question is the program given below:

#include<iostream>
#include<fstream>

using namespace std;
int main()
{
   char filename[30], ch;
   int tot=0;
   ifstream fp;
   cout<<"Enter the Name of File: ";
   cin>>filename;
   fp.open(filename, ifstream::in);
   if(!fp)
   {
      cout<<endl<<"File doesn't exist or Access denied!";
      return 0;
   }
   while(fp>>noskipws>>ch)
      tot++;
   fp.close();
   cout<<endl<<"Total Characters = "<<tot;
   cout<<endl;
   return 0;
}

The snapshot given below shows the initial output produced by above C++ program on counting total characters available in a text file:

count total characters in file c++

Now enter the name of file say codescracker.txt (the file created earlier) and press ENTER key to count and print the total number of characters like shown in the snapshot given below:

c++ program count total characters in file

Note - The noskipws is used in between file pointer fp and the character variable ch while scanning/getting the character, so that to extract and initialize all the things (i.e., whole content of file) including tab spaces, blank spaces, newlines etc.

Count Number of Words in a File

This program count and prints total number of words available in a file entered by user. Most of the code will be same with previous program except the counting part. Let's have a look at the program given below:

#include<iostream>
#include<fstream>

using namespace std;
int main()
{
   char filename[30], ch, str[1000];
   int tot=0, i=0, tot_word=0;
   ifstream fp;
   cout<<"Enter the Name of File: ";
   cin>>filename;
   fp.open(filename, ifstream::in);
   if(!fp)
   {
      cout<<endl<<"File doesn't exist or Access denied!";
      return 0;
   }
   while(fp>>noskipws>>ch)
   {
      str[tot] = ch;
      tot++;
   }
   fp.close();
   str[tot]='\0';
   while(str[i]!='\0')
   {
      if(str[i]=='\n')
      {
         if(str[i+1]!='\0' && str[i+1]!=' ')
            tot_word++;
         i++;
      }
      else if(str[i]!=' ')
         i++;
      else
      {
         if(str[i+1]!='\0' && str[i+1]!=' ')
            tot_word++;
         i++;
      }
   }
   cout<<endl<<"Total Words = "<<tot_word;
   cout<<endl;
   return 0;
}

Here is its sample run with same user input, that is codescracker.txt as the name of file:

c++ program count words in file

In above program, the statement:

str[tot]='\0';

is used to terminate the initialization of character to string str using a null terminated character ('\0'). And the following block of code:

   while(str[i]!='\0')
   {
      if(str[i]=='\n')
      {
         if(str[i+1]!='\0' && str[i+1]!=' ')
            tot_word++;
         i++;
      }
      else if(str[i]!=' ')
         i++;
      else
      {
         if(str[i+1]!='\0' && str[i+1]!=' ')
            tot_word++;
         i++;
      }
   }

is responsible to count the total number of words available in the string str. This string contains all the content of the file. Therefore, indirectly the code is used to count the total number of words in the file. In this block of code, the code:

while(str[i]!='\0')

states that the loop continues its execution until a null terminated character ('\0') arrives. And the code:

if(str[i+1]!='\0' && str[i+1]!=' ')

states that the condition evaluates to be True only if character at i+1th index is not equal to a null terminated character and also not equal to a blank space.

Count Number of Lines in File

This is I think the simplest one from all the program given here. The only extra thing we've to do in this program is only to compare the character at current index with \n and increment the variable responsible for the counting of newlines or number of lines available in the file like shown in the program given below:

#include<iostream>
#include<fstream>

using namespace std;
int main()
{
   char filename[30], ch, str[1000];
   int tot=0, i=0, tot_lines=0;
   ifstream fp;
   cout<<"Enter the Name of File: ";
   cin>>filename;
   fp.open(filename, ifstream::in);
   if(!fp)
   {
      cout<<endl<<"File doesn't exist or Access denied!";
      return 0;
   }
   while(fp>>noskipws>>ch)
   {
      str[tot] = ch;
      tot++;
   }
   fp.close();
   str[tot]='\0';
   while(str[i]!='\0')
   {
      if(str[i]=='\n')
         tot_lines++;
      i++;
   }
   tot_lines++;
   cout<<endl<<"Total Number of Lines = "<<tot_lines;
   cout<<endl;
   return 0;
}

Here is its sample run with user input codescracker.txt to count and print total number of lines available in this file like shown in the snapshot given below:

c++ program count lines in file

Total Number of Blank Spaces in File

This program is as simple as previous program. Here also, we only have to compare with ' ' a blank space with each and every character one by one like shown in the program given here:

#include<iostream>
#include<fstream>

using namespace std;
int main()
{
   char filename[30], ch, str[1000];
   int tot=0, i=0, tot_blanks=0;
   ifstream fp;
   cout<<"Enter the Name of File: ";
   cin>>filename;
   fp.open(filename, ifstream::in);
   if(!fp)
   {
      cout<<endl<<"File doesn't exist or Access denied!";
      return 0;
   }
   while(fp>>noskipws>>ch)
   {
      str[tot] = ch;
      tot++;
   }
   fp.close();
   str[tot]='\0';
   while(str[i]!='\0')
   {
      if(str[i]==' ')
         tot_blanks++;
      i++;
   }
   cout<<endl<<"Total Number of Blank Spaces = "<<tot_blanks;
   cout<<endl;
   return 0;
}

Here is the snapshot of the sample run with again same user input as of previous program, that is codescracker.txt:

c++ program count blank spaces in file

Count Vowels and Consonants in File

This is the last program of this article that count and prints total number of vowels as well as consonants available in a text file:

#include<iostream>
#include<fstream>

using namespace std;
int main()
{
   char filename[30], ch, str[1000];
   int tot=0, i=0, vowels=0, consonants=0, ascii;
   ifstream fp;
   cout<<"Enter the Name of File: ";
   cin>>filename;
   fp.open(filename, ifstream::in);
   if(!fp)
   {
      cout<<endl<<"File doesn't exist or Access denied!";
      return 0;
   }
   while(fp>>noskipws>>ch)
   {
      str[tot] = ch;
      tot++;
   }
   fp.close();
   str[tot]='\0';
   while(str[i]!='\0')
   {
      if(str[i]=='a'||str[i]=='e'||str[i]=='i'||str[i]=='o'||str[i]=='u')
         vowels++;
      else if(str[i]=='A'||str[i]=='E'||str[i]=='I'||str[i]=='O'||str[i]=='U')
         vowels++;
      else
      {
         ascii = str[i];
         if(ascii>=65 && ascii<=90)
            consonants++;
         else if(ascii>=97 && ascii<=122)
            consonants++;
      }
      i++;
   }
   cout<<endl<<"Total Number of Vowels = "<<vowels;
   cout<<endl<<"Total Number of Consonants = "<<consonants;
   cout<<endl;
   return 0;
}

The snapshot given below shows the sample run of above program on counting total number of vowels and consonants in a text file entered by user at run-time:

c++ count vowels consonants in file

The above program is created in a way that, first I've checked whether the character is a vowel or not. If not, then using else block, the character gets initialized to a variable of int type, that assigns the ASCII equivalent of the character. And using the ASCII value, I've done the thing.

Note - The ASCII values of A-Z are 65-90 and for a-z are 97-122.

You can also replace the following block of code, from above program:

      else
      {
         ascii = str[i];
         if(ascii>=65 && ascii<=90)
            consonants++;
         else if(ascii>=97 && ascii<=122)
            consonants++;
      }

with the block of code given below:

      else
      {
         if(str[i]>='A' && str[i]<='Z')
            consonants++;
         else if(str[i]>='a' && str[i]<='z')
            consonants++;
      }

The output will be same. I've provided both variety to give you the complete understanding on the topic.

C++ Online Test


« C++ Tutorial C++ Example »



© Copyright 2021. All Rights Reserved.

CodesCracker