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.
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.
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
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;
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;
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++;
}
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();
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;
}
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.