Remove extra whitespace using fstream

Oct 9, 2011 at 12:40am
Hi, I am trying to create a program that will remove all of the extra whitespace in one file, and output the result to another file. My code thus far prints only the first letter of the original file. Any help you can provide would be greatly appreciated.

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
49
50
51
52
53
#include <iostream>
#include <fstream>
#include <cctype>
#include <cstdlib>

using namespace std;

void filter_blank_spaces(ifstream& in_stream, ofstream& out_stream);

int main()
{
	ifstream fin;
	ofstream fout;

	fin.open("proj-8.dat");

	if (fin.fail())
	{
		cout << "Input file could not be opened.\n";
		exit(1);
	}

	fout.open("proj-8_2.dat");

	if (fout.fail())
	{
		cout << "Output file could not be opened.\n";
		exit(1);
	}

	filter_blank_spaces(fin, fout);
	fin.close( );
	fout.close( );
	cout << "Done.\n";

	return 0;
}

void filter_blank_spaces(ifstream& in_stream, ofstream& out_stream)
{
	char next;
	in_stream.get(next);

	do
	{
		if (isspace(next))
			out_stream << ' ';
		else
			out_stream << next;
		in_stream.get(next);
	}
	while (! in_stream.get(next));
}
Oct 9, 2011 at 12:45am
Here's one way to strip all whitespace using streams:
1
2
3
4
5
6
fstream fin( "in.txt" );
fstream fout( "out.txt" );
string s;
while( fin >> s ) {
    fout << s;
}
Oct 9, 2011 at 12:46am
Just read strings, the delimiters are ignored. You can then write the strings out with your delimiter choice.
Oct 9, 2011 at 1:08am
Thanks for the help. I modified moorecm's suggestion to add one space between each word. My only question is how would I include a "\n" or "endl" to start the second sentence in the file on a new line?
Last edited on Oct 9, 2011 at 1:14am
Oct 9, 2011 at 12:06pm
Do you just want to insert newlines or do you want to preserve the newlines as they were?

For the latter, you can try something like this:
1
2
3
4
5
6
7
while( getline( fin, s ) ) { // read a line at a time
    stringstream line( s );
    while( line >> s ) { // read the words, ignoring whitespace
        fout << s;
    }
    fout << endl; // put the newline back
}
Topic archived. No new replies allowed.