CPP program to replace multiple spaces with single space

C++ program to replace multiple spaces with single space is the third program of the same compression utility that we are trying to build in this series. The previous two programs are

  1.  C++ program to remove multi-line comments from any text file ( C/C++ style comments)
  2. C++ Program to remove single line comments from any text file ( C/C++ style comments )

The text file normally contains either multiple TAB or multiple spaces or both. In this program, we will replace all the tabs and spaces with single space. Here is the source code

/*	Program to replace multiple spaces/tab 					with		 a single space
	made by		: rakesh kumar
	file name	: multiple_space.cpp   					   file      in this    file
*/

#include
#include
using namespace std;
int main()
{
	ifstream fin("multiple_space.cpp");
	char ch;
	int count=0;
	while(fin.get(ch))
	{
		if(ch=='\t')
			ch =' ';
		if(ch==' ')
			count++;
		else
		   count=0;
		if(count<=1)	
		    cout<<ch;
	}
	fin.close();
	return 0;
}

The name of above program is the input of this program and you can see from its output that the program is able to remove multiple occurrence of spaces with single space.

multiple spaces with single space
C++ program output – replace multiple spaces with single space.
%d bloggers like this: