ifstream copied to ofstream where every string of two or more consecutive blanks is replaced by a single blank
Oct 16, 2015 at 5:55am UTC
I'm trying to write a program that takes the input from one text file and outputs a copy to a second file. The only difference is that every string of two or more consecutive blanks is replaced by a single blank.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cctype>
#include <iomanip>
using namespace std;
void remove_blanks(ifstream& unedited, ofstream& edited);
int main()
{
ifstream unedited;
ofstream edited;
unedited.open("textfile1.txt" );
if (unedited.fail())
{
cout << "Input file opening failed.\n" ;
system("pause" );
exit(1);
}
edited.open("textfile2.txt" );
if (edited.fail())
{
cout << "Output file opening failed.\n" ;
system("pause" );
exit(1);
}
remove_blanks(unedited, edited);
unedited.close();
edited.close();
system("pause" );
return 0;
}
void remove_blanks(ifstream& unedited, ofstream& edited)
{
char next, last;
unedited.get(next);
while (!unedited.eof())
{
last = next;
if (!((isspace(next)) && (isspace(last)))) // FIRST IF STATEMENT
//if (((next != ' ') && (last != ' '))) // SECOND IF STATEMENT
{
edited.put(next);
}
unedited.get(next);
}
}
The unedited text file is:
1 2 3
The lazy dog jumped over
the big brown log. Yesterday
I went to the store.
Output from FIRST IF STATEMENT:
Thelazydogjumpedoverthebigbrownlog.YesterdayIwenttothestore.
Output from SECOND IF STATEMENT:
1 2 3
Thelazydogjumpedover
thebigbrownlog.Yesterday
Iwenttothestore.
Output as it should be:
1 2 3
The lazy dog jumped over
the big brown log. Yesterday
I went to the store.
Last edited on Oct 16, 2015 at 6:16am UTC
Oct 16, 2015 at 8:00am UTC
Some small logic changes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
while (!unedited.eof())
{
last = next;
//if (!((isspace(next)) && (isspace(last)))) // FIRST IF STATEMENT
if (((next != ' ' ) && (last == ' ' ))) // SECOND IF STATEMENT
{
edited.put(' ' );
edited.put(next);
}
else if (next != ' ' ) // Note
edited.put(next);
last = next;
unedited.get(next);
}
Oct 18, 2015 at 6:20am UTC
Thank you. It worked. I had to make one more change. It wouldn't compile until I initialized the char last. I don't think it matters what, so I initialized it to 'z'.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
void remove_blanks(ifstream& unedited, ofstream& edited)
{
char next, last = 'z' ;
unedited.get(next);
while (!unedited.eof())
{
if ((next != ' ' ) && (last == ' ' ))
{
edited.put(' ' );
edited.put(next);
}
else if (next != ' ' )
{
edited.put(next);
}
last = next;
unedited.get(next);
}
}
Topic archived. No new replies allowed.