I stumbled upon strange behavior of string::substr. Normally I code on Windows 7 in Eclipse+MinGW, but when I was working on my laptop, using Eclipse in Linux (Ubuntu 12.04) I noticed difference in result.
I was working with vector< string > filled with lines of text. One of steps was to remove last character from line.
In win7 Eclipse I did:
for( int i = 0; i < (int)vectorOfLines.size(); i++ )
{
vectorOfTrimmedLines.push_back( ((string)vectorOfLines.at(i)).substr(0, ((string)vectorOfLines.at(i)).size()-1) );
}
and it works like intended (removing last character from each line)
But in Linux this code do not trim. Instead I needed to do it like this:
// -2 instead -1 character
vectorOfTrimmedLines.push_back( ((string)vectorOfLines.at(i)).substr(0, ((string)vectorOfLines.at(i)).size()-2) );
or using another method:
vectorOfTrimmedLines.push_back( ((string)vectorOfLines.at(i)).replace( (((string)vectorOfLines.at(i)).size()-2),1,"",0 ));
Ofcourse Linux methods work wrong way on windows (trimming 2 last characters, or replacing one before last).
The problem seems to be that myString.size() return number of characters in Windows, but in Linux it returns number of characters + 1. Could it be that new line character is counted on Linux?
As a newbie in C++ and programming general, I wonder why it is like that, and how can this be done to be platform independent.
Another thing that I wonder is : which method is preferable (faster) substr or replace?
Edit: Method used to fill string s this function i wrote:
vector< string > ReadFile( string pathToFile )
{
// opening file
ifstream myFile;
myFile.open( pathToFile.c_str() );
// vector of strings that is returned by this function, contains file line by line
vector< string > vectorOfLines;
// check if the file is open and then read file line by line to string element of vector
if( myFile.is_open() )
{
string line; // this will contain the data read from current the file
while( getline( myFile, line ) ) // until last line in file
{
vectorOfLines.push_back( line ); // add current line to new string element in vector
}
myFile.close(); // close the file
}
// if file does not exist
else
{
cerr << "Unable to open file." << endl; // if the file is not open output
//throw;
}
return vectorOfLines; // return vector of lines from file
}