I have a piece of code which reads in a line from a file, then removes the whitespace and tells you the length of the string. In windows it works as I expect it to, however in linux it returns a different result.
Code:
// Find how many characters are in the first line
std::string line;
std::ifstream map ("level1.map");
getline(map,line);
// Remove whitespace from the string to get the useful length of line
for ( unsigned int i = 0, j ; i < line.length( ) ; ++ i )
{
if ( line [i] == ' ' )
{
for ( j = i + 1; j < line.length ( ) ; ++j )
{
if ( line [j] != ' ' )
break ;
}
cout << j;
line = line.erase ( i, (j - i) ) ;
}
}
// Output
cout << line.size() << endl;
It’s essentially just trying to determine how many tile columns there are in the map file, where the map is formatted thusly on each line:
2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2
And so whitespace needs to be removed.
In windows given an initial line length of 160 the end length is 80, however when compiled in linux the initial length is 160, but the end length is 81. The only place the value becomes different appears to be after line = line.erase ( i, (j – i) ) ;
Any ideas why this is happening?
I think therefromhere is right. The solution is two-fold:
Always set the
binaryflag when constructing anifstreamorofstream. Let your code handle newlines however it wants, but don’t rely on non-portable newline conversion.Choose a standard format (LF or CRLF) for the tile map, and output that format on all platforms.
Then, it will work the same provided you’re testing with the same
level1.map.