CPP program to remove single line comment from text file – C/C++ style Comments

In this C++ program we will remove all single line comments that start with double slash(//). This program is a part of the same compression utility program in which we will input any text file and will receive output file without any single line comment.

C++ Program to remove multi-line comment

The program is developed in Windows environment using Dev C++ IDE. Here is the source code written in C++ language.

/*		Program to remove single line comment from any text file
		made by :	rakesh kumar
*/

#include
#include
using namespace std;

// global function to remove single line comment
void remove_single_comment(char source[], char dest[]){
	ifstream fin(source);
	ofstream fout(dest);
	char ch;
	while(!fin.eof())
	{
		fin.get(ch);
		if(ch=='/')
		  {
		  	 fin.get(ch);
		  	 if(ch=='/')
		  	    {	while(!fin.eof())
				   {
				   	fin.get(ch);
				   	if(ch=='\n'||ch=='\r')  // remove all until end of line from the output file
				   		break;
				   }
			    }
			  else
			    fout<<"/"<<ch;
		  }
		else
			fout<<ch;
		
	}
	fin.close();
	fout.close();
}
int main()
{
	char source[]="remove_single_line_comment.cpp";
	char dest[]="temp.cpp";
	remove_single_comment(source,dest);
	ifstream fin(dest);
	char ch;
	while(fin.get(ch))
		cout<<ch;
	fin.close();
	return 0;
}

Now in this code the name of our own program is “remove_comment_single_line.cpp” which is the program itself and produces an output file”temp.cpp”. The content of temp.cpp file is produced here as its output.

C++ program to remove single line comment
remove Single line comment program output
If you like CBSEToaday and would like to contribute, you can also write an article using submit article or mail your article to contribute@cbsetoday.com See your article appearing on the cbsetoday.com main page and help other students/teachers.