Remove the Blank Lines from a Text File in C++

In this tutorial, we will learn about How to remove the blank lines from a text file in C++.

The text file keeps data in ASCII characters. In-text files, There is a special character known as EOL (End Of Line) character which terminates the line of text. When we read or write End of line character certain internal translations takes place.

getline() function

The getline() function is a part of <string.h> header file.
This function takes the characters from the input and stores them into the string until the EOL character is found.

C++ program to remove blank lines from a text file

Now, let us write the code to illustrate the same.
NOTE: I have written this code using an online IDE platform.

#include <bits/stdc++.h> 
using namespace std; 

void blank_line(const char *file_name)
{	 
  ifstream fin(file_name);    
  
  ofstream fout;                
  fout.open("temp.txt", ios::out);
  
  string str;
  while(getline(fin,str))
  { 
    while (str.length()==0 ) 
       getline(fin,str); 	
  
    fout<<str<<endl;
  }
  fout.close();  
  fin.close();	

  remove(file_name);        
  rename("temp.txt", file_name);
}
int main()
{
  blank_line("bl.txt");
  return 0;
}

Create a text file by the name “bl.txt”.
Enter data in it.

Output:

Text file content:

I 

have

written 

this 

code 

in C++.

Now after compiling,

I 
have
written 
this 
code 
in C++.

Explanation:

In this code, first of all, the header file used contains all the standard header files in it. A function is defined to remove the blank lines from the text file. We get the data using the getline() function which stores the data as a string. This function removes the blank lines from the text file.

I hope that this will help you to solve your problem.

Also, read: Fetching a random line from a text file in C++

 

Leave a Reply

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