+ -
当前位置:首页 → 问答吧 → ostringstream返回c字符串的问题

ostringstream返回c字符串的问题

时间:2011-12-18

来源:互联网

ostringstream oss;
oss << "GET / HTTP/1.1\r\nHost: www.csdn.net\r\n\r\n";
const char * buf = oss.str().c_str();
cout << buf << endl; //乱码,为什么?
cout << oss.str().c_str(); //可以

作者: jronald   发布时间: 2011-12-18

C/C++ code

#include <iostream>
#include <sstream>
using namespace std;
int main()
{
    ostringstream oss;
    oss << "GET / HTTP/1.1\r\nHost: www.csdn.net\r\n\r\n";
    char *buf = new char[oss.str().length() + 1];
    strcpy(buf , oss.str().c_str());
    cout << buf << endl; //乱码,为什么?
    cout << oss.str().c_str(); //可以
    return 0;
}

作者: hnuqinhuan   发布时间: 2011-12-18

c_str返回的是一个临时对象 已经返回就析构了 你当然得到的是乱码

作者: hnuqinhuan   发布时间: 2011-12-18

Converts the contents of a string as a C-style, null-terminated string.
const value_type *c_str( ) const;  

Return Value:
A pointer to the C-style version of the invoking string. The pointer value is not valid after calling a non-const function, including the destructor, in the basic_string class on the object.

作者: yaningfan   发布时间: 2011-12-18

oss.str()返回的是个临时的string对象吧

作者: yaningfan   发布时间: 2011-12-18

C/C++ code

#include<iostream>
#include <string>
#include <sstream>

using std::cout;
using std::endl;
using std::ostringstream;
using std::string;

int main()
{
    ostringstream oss;
    oss << "GET / HTTP/1.1\nHost: www.csdn.net";
    string str(oss.str());
    const char *buf = str.c_str();
    cout << buf << endl;//
}

作者: mougaidong   发布时间: 2011-12-18

oss还没析构啊,那指针怎么就无效了?

作者: jronald   发布时间: 2011-12-18

引用 6 楼 jronald 的回复:

oss还没析构啊,那指针怎么就无效了?


因为,指针不是指向oss的数据成员,而是一个函数返回的临时对象的数据成员,它析构了。看看楼上的例子就明白了

作者: mougaidong   发布时间: 2011-12-18

str()返回的是临时string.

作者: qq120848369   发布时间: 2011-12-18