tags:

views:

77

answers:

4

I have a wstringstream:

wstringstream sstream;
AlterSstream(sstream);

wstringstream bar_stream;

bar_stream << sstream;
bar_stream << "foo";

MessageBoxW(
  NULL,
  bar_stream.str().c_str(),
  L"subject",
  MB_OK
);

This outputs a long string that looks nothing like what I put in it in AlterSstream():

00000000002CEC58foo

AlterSstream:

void AlterSstream(wstringstream& outStream)
{
    outStream << "odp";
}

Why is this happening? If I print out sstream directly, it works fine, but printing out bar_stream creates the problem. I'm guessing that the << operator doesn't work the way I think it does between two streams?

UPDATE: Sorry, I had left a bit of code out originally. It is fixed above.

+1  A: 

Have you tried L"odp"?

swegi
mmm good idea but that didn't work - same problem as before.
Rosarch
+3  A: 

Looks like the compiler selected the version of operator<< that accepts a void* argument and prints its 64-bit address in hexadecimal. The text-printing version of operator<< is a template that takes the same kind of character as the stream's representation, which in your case is wchar_t. You've passed it an array of char; use a wide-character literal instead, as Swegi's answer suggests:

outStream << L"odp";
Rob Kennedy
I was thinking the same, but then why does the compiler pick the right overload for sstream << "foo";? The only difference is that op<< "odp" is called with the reference to sstream in the Alterstream function.
tpdi
On the other hand, if the compiler used the `void*` version inside `AlterSstream`, then it should have also selected that version for inserting `foo`. I have no explanation for the different behaviors. Are you sure you copied and pasted your real code into your question?
Rob Kennedy
Actually, I didn't copy the code entirely correctly. I have corrected the OP.
Rosarch
+3  A: 

There is no overload to copy from stream to stream. You need to change the line:

bar_stream << sstream;

to:

bar_stream << sstream.str();
dig
Nitpick: no over*LOAD*.
tpdi
you are completely right. fixed.
dig
A: 

Ok, with your update you revealed the problem:

bar_stream << sstream;

wstringstream is:

typedef basic_stringstream<wchar_t> wstringstream;

basic_stringstream is-a basic_iostream, which is-a basic_ostream (and a basic_istream, but we don't care about that part) which is-a basic_ios which is-a ios_base.

But there's no basic_ostream& operator<<(basic_ostream&);; I'm not sure which overload the compiler is using, but it appears from the output to be basic_stringstream& basic_stringstream::operator<<(void *p), which outputs the pointer's value in hex.

If you want to copy the sstream's data, use the wstringstream ctor that takes a const basic_string. passing it a copy of the original wstringstream's internal string:

wstringstream bar_stream( sstream.str() ) ;
tpdi