Hi all,
I'm busy writing a generic textfile reader class and I'm struggling to write the code to deal correctly with end-of-line (EOL) characters for Mac, Linux and Windows.
I've done a fair bit of reading on the issue and I came up with the following function within my TextFileReader class to strip EOL characters once I've read the contents of a textfile using getline( ) and stored the strings in a map.
//! Strip End-Of-Line characters.
void TextFileReader::stripEndOfLineCharacters( )
{
// Search through container of data and remove newline characters.
string::size_type stringPosition_ = 0;
string searchString_ = "\r";
string replaceString_ = "";
for ( unsigned int i = 0; i < 1; i++ )
{
for ( iteratorContainerOfDataFromFile_
= containerOfDataFromFile_.begin( );
iteratorContainerOfDataFromFile_
!= containerOfDataFromFile_.end( );
iteratorContainerOfDataFromFile_++ )
{
while ( ( stringPosition_ = iteratorContainerOfDataFromFile_
->second.find( searchString_,
stringPosition_ ) ) != string::npos )
{
// Replace search string with replace string.
iteratorContainerOfDataFromFile_->second
.replace( stringPosition_, searchString_.size( ),
replaceString_ );
// Advance string position.
stringPosition_++;
}
}
// Switch search string.
searchString_ = "\n";
}
}
I thought that this would eliminate all EOL characters cross-platform but that doesn't seem to be the case. It works fine on my Mac, running Mac OS 10.5.8. It doesn't seem to work on Windows systems though. Strangely, on Windows systems running this function on strips the EOL character for the first string in the map and the rest of them are still one character too long.
This leads me to thinking that maybe I can't just replace the "\r" and "\n" characters, but everything I read suggests that it's the combination of the two that Windows uses to represent EOL characters.
Any, maybe there's a better way of doing this.
I'd really appreciate any input as this is a really small bug that's preventing me from moving on.
Thanks a lot in advance!
Kartik