• Advertisement
Sign in to follow this  

wstringstream not working?

This topic is 1770 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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 this post


Link to post
Share on other sites
Advertisement

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.).

Edited by Paradigm Shifter

Share this post


Link to post
Share on other sites

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 this post


Link to post
Share on other sites
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 this post


Link to post
Share on other sites

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...

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement