Counting Characters in a File Using C++

C++C++Beginner
Practice Now

Introduction

In this lab, we will learn how to count the occurrence of a character in a file using C++ programming. We will create a C++ program that reads a file and counts the number of times a particular character occurs in the file.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("`C++`")) -.-> cpp/BasicsGroup(["`Basics`"]) cpp(("`C++`")) -.-> cpp/ControlFlowGroup(["`Control Flow`"]) cpp/BasicsGroup -.-> cpp/variables("`Variables`") cpp/BasicsGroup -.-> cpp/data_types("`Data Types`") cpp/BasicsGroup -.-> cpp/operators("`Operators`") cpp/ControlFlowGroup -.-> cpp/conditions("`Conditions`") cpp/ControlFlowGroup -.-> cpp/while_loop("`While Loop`") subgraph Lab Skills cpp/variables -.-> lab-96159{{"`Counting Characters in a File Using C++`"}} cpp/data_types -.-> lab-96159{{"`Counting Characters in a File Using C++`"}} cpp/operators -.-> lab-96159{{"`Counting Characters in a File Using C++`"}} cpp/conditions -.-> lab-96159{{"`Counting Characters in a File Using C++`"}} cpp/while_loop -.-> lab-96159{{"`Counting Characters in a File Using C++`"}} end

Create a File

First, we need to create a file with some text in it. Let's create a file named example.txt in the ~/project directory, and write some text in it. For this, execute the following command in the terminal:

echo -e "This is an example file\nIt contains some text" > ~/project/example.txt

Include Header Files

In this step, include the required header files, iostream, and fstream. iostream is required for input and output operations, and fstream is required for file handling operations. Create a new file named main.cpp in the ~/project directory, and open it in a text editor.

#include <iostream>
#include <fstream>
using namespace std;

Define Variables

In this step, we define the variables filename for the input file, ch to store the current character that the program is reading, and count to count the number of times the character occurs in the file.

string filename = "example.txt";
char ch;
int count = 0;

Open and Read Input File

In this step, we create an ifstream object to open the input file example.txt in read mode. We then use a while loop to read the file character by character. We use the get() function to read one character at a time from the file. We check if the read character matches the character we want to count. If the current character matches, we increment the count variable.

ifstream fin(filename,ios::in);

while(fin.get(ch)){
    if(ch == 'e')
        count++;
}

Display Result

In this step, we display the number of times the character appears in the file. We also close the input file.

cout << "The number of times 'e' appears in file is: " << count;
fin.close();

Compile and Run the program

In this step, we compile the C++ program and execute it to count the occurrence of a character in the file. Open the terminal and navigate to the ~/project directory, and execute the following command:

g++ main.cpp -o main && ./main

This will compile and run the main.cpp file. The output will show the number of times the character appears in the file.

The final code of main.cpp file is as follows:

#include <iostream>
#include <fstream>
using namespace std;

int main(){
    string filename = "example.txt";
    char ch;
    int count = 0;

    ifstream fin(filename,ios::in);

    while(fin.get(ch)){
        if(ch == 'e')
            count++;
    }

    cout << "The number of times 'e' appears in file is: " << count;
    fin.close();

    return 0;
}

Summary

In this lab, we have learned how to count the number of times a particular character appears in a file using C++ programming. We read a file character by character using an ifstream object and counted the number of times the required character appears. We also displayed the result on the console.

Other C++ Tutorials you may like