SOURCE FILE: ex0905.cpp


//
// Example 9.5. Program to make a copy of a file, 
// removing multiple blanks
// Files: ex0905.dat   - input file of characters 
//        ex0905ot.dat - output file that is a copy of ex0905.dat
//                       with multiple blanks replaced by one blank
//

#include <fstream.h>
#include <assert.h>

int main(void)
{
   void RemoveBlanks(ofstream&, ifstream&);
   
   ifstream infile("ex0905.dat");
   assert(infile);

   ofstream outfile("ex0905ot.dat");
   assert(outfile);
   
   RemoveBlanks(outfile, infile);

   return 0;
}

//
// Function to copy an input file to an output file,
// removing multiple blanks
// Pre:  outfile is an ofstream output file stream.
//       infile is an ifstream input file stream.
// Post: The input file has been copied to the output
//       file with multiple blanks replaced by one blank.
//

void RemoveBlanks(ofstream& outfile, ifstream& infile)
{
   char NewChar,   // character to read and write 
        PrevChar;  // previous character
    
   // copy first character if the input file is not empty  
   if (infile.get(NewChar)) 
   {
      outfile << NewChar;
      PrevChar = NewChar;
   }
   
   // copy the rest of the file, but do not copy a blank
   // if the previous character was a blank
   while (infile.get(NewChar))
   {
      if (!(NewChar == ' ' && PrevChar == ' '))
         outfile << NewChar;
      PrevChar = NewChar;
   }
 
   assert(infile.eof());
}