-
deleting extra spaces
[color=dark-blue]-Hello everyone :D.. I have this function it is suppose to copy an input file that contains words with different numbers of spaces between them to an output file while deleting any extra spaces between the words… so the output file is identical to the input file except it has only one space between each word… I have written this function in two different ways but both have some problems….…[/color]
-The problem in this function that it writes all the lines in the input file to only a single line in the output file …
Code:
void del_extra_spaces ( ifstream& input_file , ofstream& output_file )
{
char word[30] ;
while (! input_file.eof() )
{ input_file >> word ;
output_file << word ;
output_file << " " ;
}
}
-This function writes all the lines in the input file to only a single line in the output file with no space between the words…
Code:
void del_extra_spaces ( ifstream& input_file , ofstream& output_file )
{
char c ;
input_file.get ( c ) ;
while (! input_file.eof() )
{
if ( ! isspace ( c ) )
{
output_file.put ( c ) ;
input_file.get ( c ) ;
}
If ( isspace ( c ) )
input_file.get ( c ) ;
}
}
-Thank you :)…
-
Your first function uses the overloaded operator ">>" which skips past the newline character in the input file, which is why the output is in one line.
In your second function, you neglect to actually write the space to the file.
Try this: (I haven't compiled or tried it, but it should work)
Code:
void del_extra_spaces ( ifstream& input_file , ofstream&
output_file )
{
char c ;
input_file.get ( c ) ;
while ( !input_file.eof() )
{
if ( c != " " )
{
output_file.put ( c );
input_file.get ( c );
}
else
{
//We found a space, but we only want one space,
//so read all spaces and place one space in
output file
do{
input_file.get ( c );
}
while( c == " " && !input_file.eof() );
//Are we at the end of the file?
if( !input_file.eof() )
output_file.put ( " " );
}
}
}