editing text space in files

I'm trying to take a file that has extra spaces in it, and correct it to eliminate each extra space and simply write one space between each word. The file data.dat contains this (with spaces explained since it automatically corrects it on here)-

This is (2 spaces) the (3 spaces) input (2 spaces) file.

My code seems to be skipping alternating words and produces

is input file. (spacing is correct)

I have the feeling im messing up in my getline declarations, but my code is:

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
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

void fixSpace (ifstream& fin, ofstream& fout);

int main (void)
{
ifstream fin;
ofstream fout;

fin.open("data.dat");
if(fin.fail())
{
        cout<<"Input file opening failed."<<endl;
        exit(1);
}

fout.open("dataclean.dat");
if(fout.fail())
{
        cout<<"Output file opening failed."<<endl;
        exit(1);
}

fixSpace(fin,fout);

fout.close();
fin.close();

return 0;
}


void fixSpace (ifstream& fin, ofstream& fout)
{
string next="";
getline(fin,next,' ');
while(! getline(fin,next,' ').eof())
{
        if (next=="")
                fout<<" ";
        else
                fout<<next;
        getline(fin,next,' ');
}

return;
}


-Any hints on how to correct this skipping would be very useful.
You are calling getline() twice in your loop. Once at the beginning (41), and again at the end (47). You may also want to loop on simply !getline() since there could be an error reading the file that doesn't set the eof bit, and use next.empty() for your condition on line 43.
Yah it was still giving me trouble so I changed it to process the file by each character. Thanks for the help though.


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
void fixSpace (ifstream& fin, ofstream& fout)
{
char next;
int track=0;

fin.get(next);
while(! fin.eof())
{
if(next!=' ')
{
        fout<<next;
        track=0;
}
else
{
        if (track==0)
        {
                fout<<next;
                track++;
        }
        else
                track++;
}
fin.get(next);
}
return;
}


Looks like you already figured it out, but you may want to look at the file_stream.peek(), it may help you in your endeavors =)
Topic archived. No new replies allowed.