Std :: ostringstream does not return a valid string

I am trying to use std :: ostringstream to convert a number to a string (char *), but it does not seem to work. Here is 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; } 

There is simply no text in the message box that appears.

This makes me think that calling out.str().c_str() returns the wrong string, but I'm not sure. Since I cut this program so far, I still run into a problem, I must have made an awkwardly simple mistake. Help is appreciated!

+6
c ++ std winapi ostringstream
source share
1 answer

out.str() returns the value of std::string by value, which means that you are calling .c_str() temporarily. Therefore, by the time intString initialized, it already points to invalid (destroyed) data.

Compose the result of .str() and work with this:

 std::string const& str = out.str(); char const* intString = str.c_str(); 
+12
source share

All Articles