I am trying to read data from a comma delimited file into strings. Furthermore, I wish to remove extra spaces from string.
I have managed to implement a working solution, but I am interested if this can be done more efficiently. My main goal is to remove the temporary string initialization with default string size ( std::string lName( 100, 0 );
) since data in the file is of variable length.
Also, if you have some constructive advice I would appreciate it.
I am using MS Visual Studio 2008.
Here is the SSCCE example :
#include <iostream>
#include <algorithm>
#include <string>
#include <fstream>
// helper function for removing extra spaces
void removeSpace( std::string &str )
{
str.erase( std::remove( str.begin(), str.end(), ' ' ), str.end() );
}
int main()
{
//========== let us construct a test file =====================//
//===== format is Last Name, First Name, Gender, Color, Birth Date =======//
std::ofstream os;
os.open( "test.txt" );
// first row
os << " Smith ," << " John ," << " Male , "
<< " Green , " << " 6 / 7 / 1960 \n";
// second row
os << " Mortensen ," << " Mike ," << " Male , "
<< " Red , " << "5/5/ 1975 \n";
// third row
os << " Johnson ," << " Ann ," << " Female , "
<< " Blue , " << " 4/ 4 /1985 \n";
os.close();
// now let us read data from it
std::ifstream g;
g.open( "test.txt" );
if( g.is_open() )
{
while( !g.eof() )
{
// temporary strings
std::string lName( 100, 0 );
std::string fName( 100, 0 );
std::string gen( 100, 0 );
std::string clr( 100, 0 );
std::string date( 100, 0 );
// get data from file
g.getline( &lName[0], 100, ',' );
g.getline( &fName[0], 100, ',' );
g.getline( &gen[0], 100, ',' );
g.getline( &clr[0], 100, ',' );
g.getline( &date[0], 100 );
// remove extra spaces from strings
removeSpace( lName );
removeSpace( fName );
removeSpace( gen );
removeSpace( clr );
removeSpace( date );
// display the result
std::cout << lName.c_str()
<< ' ' << fName.c_str()
<< ' ' << gen.c_str()
<< ' ' << clr.c_str()
<< ' ' << date.c_str()
<< std::endl;
//cleanup
lName.clear();
fName.clear();
gen.clear();
clr.clear();
date.clear();
}
g.close();
}
// since our SSCCE example is done, let us delete the test file
if( 0 != std::remove( "test.txt" ) )
std::cout << "Couldn't delete test file!\n\n";
else
std::cout << "Successfully deleted test file!\n\n";
return 0;
}
EDIT:
Following advice from member WhozCraig, I was able to produce an improvement. For brevity, I will only post the while
loop:
while( !g.eof() )
{
// temporary strings
std::string line;
if( ! std::getline( g, line ) )
break;
std::istringstream iss(line);
while( iss )
{
std::string str;
if ( ! std::getline( iss, str, ',' ) )
break;
// remove excess spaces
removeSpace( str );
// output the result
std:: cout << str.c_str() << ' ';
}
std::cout << std::endl;
}