Nick Heiner
Nick Heiner

Reputation: 122392

Trouble with wstringstream

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.

Upvotes: 2

Views: 2185

Answers (4)

Dig
Dig

Reputation: 3950

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

bar_stream << sstream;

to:

bar_stream << sstream.str();

Upvotes: 3

tpdi
tpdi

Reputation: 35141

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() ) ;

Upvotes: 0

Rob Kennedy
Rob Kennedy

Reputation: 163247

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";

Upvotes: 3

swegi
swegi

Reputation: 4102

Have you tried L"odp"?

Upvotes: 1

Related Questions