std::ostringstream isn't returning a valid string

可紊 提交于 2019-11-27 06:56:26

问题


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!


回答1:


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


来源:https://stackoverflow.com/questions/11164982/stdostringstream-isnt-returning-a-valid-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!