I spent about 4 hours yesterday trying to fix this issue in my code. I simplified the problem to the example below.
The idea is to store a string in a stringstream
ending with std::ends
, then retrieve it later and compare it to the original string.
#include <sstream>
#include <iostream>
#include <string>
int main( int argc, char** argv )
{
const std::string HELLO( "hello" );
std::stringstream testStream;
testStream << HELLO << std::ends;
std::string hi = testStream.str();
if( HELLO == hi )
{
std::cout << HELLO << "==" << hi << std::endl;
}
return 0;
}
As you can probably guess, the above code when executed will not print anything out.
Although, if printed out, or looked at in the debugger (VS2005), HELLO
and hi
look identical, their .length()
in fact differs by 1. That's what I am guessing is causing the ==
operator to fail.
My question is why. I do not understand why std::ends
is an invisible character added to string hi
, making hi
and HELLO
different lengths even though they have identical content. Moreover, this invisible character does not get trimmed with boost trim. However, if you use strcmp
to compare .c_str()
of the two strings, the comparison works correctly.
The reason I used std::ends
in the first place is because I've had issues in the past with stringstream
retaining garbage data at the end of the stream. std::ends
solved that for me.