wstringstream not working?

Recommended Posts

Juliean    7068

Hello,

I want to write a function that converts a float value to a LPCWSTR, like this:

    LPCWSTR ToString(float value) {
wstringstream stream;
wstring string;
stream << value;
stream >> string;
return string.c_str();
}

But, as you can see in the attached file, it only outputs weird letters. The debugger tells me that this is really the content of the stream after I "<<" the float value. It does not depend on the exact value oft he float, and it also happens when I try to insert a normal string, or int. Any ideas why this could be failing? Both sstream and string are included, and as far as my old work with the string streams and the dozens of internet examples go, I'm doing everything right, despite that bug...

Share on other sites

You are returning a pointer to owned by an object that lives on the stack... so it goes out of scope and is destroyed.

Either return a wstring directly (or through a reference/pointer), or (not recommended) have the caller supply a buffer which you fill (and opens up potential for buffer overwrites, etc.).

Share on other sites
Juliean    7068

Now thats what you call a huge fail (of mine) - since the content of the wstringstream looked just like the output my textboxes showed (but it obviously wasn't the same), I didn't even think to check if it was a scoping issue. Thank you.

Share on other sites
iMalc    2466
Were you really able to declare a wstring variable named string?

LPCWSTR is just a const wchar_t*, i.e. a pointer to the text. When you aren't providing a buffer for it to store the text in, you need to ask yourself the question of where it is going to put that text and how and when is it going to be cleaned up. Edited by iMalc

Share on other sites
Juliean    7068

Were you really able to declare a wstring variable named string?

Yeah, that did indeed work.

LPCWSTR is just a const wchar_t*, i.e. a pointer to the text. When you aren't providing a buffer for it to store the text in, you need to ask yourself the question of where it is going to put that text and how and when is it going to be cleaned up.

You are totally right, I feel a bit emberrased that such a mistake did happen now, because I had a similar issue when storing LPCWSTR's as map keys some time ago...