How to find substring from text file in C++

Hello guys in this tutorial, we learn how to find substring from a text file in C++. To understand this topic we first need to understand file handling C++. In file handling, we read, write and create files ( example text file) which are stored in drive and disc or we can say File which created for permanent storage of data.

We will use the header file when we are dealing with files. There are three types of class which are in the program. These are the following.

  1. ofstream – It is used for writing in the file.
  2. ifstream  – It is used for reading a file.
  3. fstream   – It is used for both reading and writing a file.

getline()

It is a function that comes under <string> header file. It used to read string but it is different because it read the whole line no matter blank spaces are between a string.

Find substring from text file in C++

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

int main () {
 
   string substring;   // declaring subtring variable.
   
   cout<<"Enter subtring"<<endl;  
    
   cin>>substring;      //taking subtring as input.
   
  ifstream file_text ("Text.txt");  // creating file_text object of ifstream type.
  
  string x;   
  
  bool ans=false;   // declaring ans variable which will get information if substring present or not.
  
  int line=1;   // it will count line and give an answer on which line we get a substring.
  
  if (file_text.is_open())       //is_open open the text file.
  {
    while ( getline (file_text,x) )    
    {
      if (x.find(substring, 0) != string::npos) {
        {
        	
        	cout<<"substring is present at line "<<line<<endl;
        	ans=true;     // if substring present make ans variable true.
    }
    
    line++;
    }
    file_text.close(); //to close text file.
  }
}
  else 
  cout << "Unable to open file"; 
  
  if(!ans)   // if subtring not present.
  cout<<"subtring not present is present"<<endl;

  return 0;
}

Also read:

Leave a Reply

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