why don't you do this the easy way by using the ifstream >> operator to remove all white space between words with output the word just read with one space
string word;
while( infile >> word)
outfile << word << " ";
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
>Make simple things easy.
Here, here. But what about the newlines and/or tabs?
iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
>But what about the newlines and/or tabs?
Indeed. And what about such monstrosities as "\t \n\n\t"? Does "extra whitespace" refer to adjacent whitespace characters of the same value, any value that isspace returns true for, or are we only working with the ' ' character? The problem doesn't seem to be well defined.
>I have read about peek() and putback().
Unnecessary. You can save the last character read from the stream and use it as a state to process the next character:
char last = 0;
char ch;
while ( in.get ( ch ) ) {
if ( ch == ' ' && last == ' ' )
continue;
out.put ( ch );
last = ch;
}
A good rule of thumb is that if you think you need to peek or putback on a stream, you probably need to improve your design.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
tabs are considered white space so they are treated just like spaces. But you (jamthwee) are correct about newlines, so my previous suggestion will not work. But there is hope. Use getline() to read the entire line then stringstream to split it up into individual words similar to what I posted before. I was about to post the solution, but then I would be doing the OPs homework for him wouldn't I ?
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343