In need of some help with a programming project which reads text from one file and places it in a 2nd file, which will be identical to the first file with the exception of any string of two or more consecutive blanks being replaced by a single space/blank, eliminating extra blank/space characters from the file.

Thanks in advance for your help!!!


The text I am using is as follows and has been named/saved as text_1.txt:

When the long   smelly fish      jumps  over the short         clean fish  it  opens   its gills      so that it can   fly.

Code:

//
// Program reads text from one file and writes an edited version
// of the same text to a new file. The edited version will be 
// identical in text, except the program will remove every string
// of two or more consecutive blanks and replace with a single blank.
//

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

void no_space(ifstream& text_1, ofstream& text_out);

int main()
{   
    int count = 0;
    char a;
    
    ifstream in_stream;
    ofstream out_stream;
    
    in_stream.open("text_1.txt");
    if(in_stream.fail( ))
    {
      cout << "Input file opening failed!\n";
      exit(1);
    }
    
    out_stream.open("text_out.txt");
    if(out_stream.fail( ))
    {
      cout << "Output file opening failed!\n";
      exit(1);
    }
    
    while (!in_stream.eof( ))
    {
          in_stream.get(a);
          
          if(isspace(a))
               count++;
          
          if(isspace(a) && count >= 2);
          {
               cout << "";
               count = 0;
          }
          
          else
          {
              cout << a;
              out_stream << a;
          }
    }
   
    in_stream.close( );
    out_stream.close( );
    
    cout << "End of editing files.\n";
    
    system("pause"); 

    return 0;   
}

line 37: never use eof() because it doesn't work the way you think it does.

You can easily read words one word at a time and ignore all white space by using the stream's >> operator

a combination of stringstream and fstream's >> operator should complete your program. stringstream is subclass of fstream so it has all the same functions/operators

string line;
while( getline(infile, line) )
{
     // split the line up into words using 
     // stringstream's >> operator then output a "\n" at the end
}

you could also use the algorithm std::unique_copy .

#include <iostream>
#include <fstream>
#include <vector>
#include <iterator>
#include <algorithm>

struct consecutive_blanks
{
  bool operator() ( char first, char next ) const
  { return first==' ' && next==' ' ; }
};

int main()
{
  std::ifstream fin( "text_1.txt" ) ;
  fin >> std::noskipws ;
  std::ofstream fout("text_out.txt") ;
  std::istream_iterator<char> begin(fin), end ;
  std::ostream_iterator<char> dest(fout) ;
  std::unique_copy( begin, end, dest, consecutive_blanks() ) ;
}
This question has already been answered. Start a new discussion instead.