std :: ostringstream不返回有效的字符串 [英] std::ostringstream isn't returning a valid string

查看:569
本文介绍了std :: ostringstream不返回有效的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用std :: ostringstream将一个数字转换为字符串(char *),但它似乎并不工作。这里是我有的代码:

  #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;
}

生成的消息框中没有文本。



这让我相信,调用 out.str()。c_str()字符串,但我不确定。因为我已经裁剪这个程序到目前为止仍然有问题,我必须做一个尴尬的简单的错误。

$ <$>

out.str()返回一个 std :: string 按值,这意味着你正在调用 .c_str()一个临时的。因此,在 intString 初始化时,它已经指向无效(已销毁)的数据。



.str()的结果:

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


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!

解决方案

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

这篇关于std :: ostringstream不返回有效的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆