Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::ostringstream isn't returning a valid string

I'm trying to use std::ostringstream to convert a number into a string (char *), but it doesn't seem to be working. Here's the code I have:

#include <windows.h>
#include <sstream>

int main()
{
    std::ostringstream out;
    out << 1234;

    const char *intString = out.str().c_str();

    MessageBox(NULL, intString, intString, MB_OK|MB_ICONEXCLAMATION);

    return 0;
}

The resulting message box simply has no text in it.

This leads me to believe that the call to out.str().c_str() is returning an invalid string, but I'm not sure. Since I've trimmed this program down so far an am still getting the problem, I must have made an embarrassingly simple mistake. Help is appreciated!

like image 311
AutoBotAM Avatar asked Jun 22 '12 22:06

AutoBotAM


1 Answers

out.str() returns a std::string by value, which means that you are calling .c_str() on a temporary. Consequently, by the time intString is initialized, it is already pointing at invalid (destroyed) data.

Cache the result of .str() and work with that:

std::string const& str = out.str();
char const* intString = str.c_str();
like image 84
ildjarn Avatar answered Nov 15 '22 06:11

ildjarn