取得std::ostringstream里的内容可以通过str()和str(string&)成员函数。由于str()返回的是临时对象,因而会有如下误用:
const
char
*
pBuffer
=
oss.str().c_str();
pBuffer指向的内存已被析够!
测试代码:
ostringstream oss;
oss << " something you like " << endl;
// can't work!
const char * szData1 = oss.str().c_str();
// work!
std::string ss = oss.str();
const char * szData2 = ss.c_str();
oss << " something you like " << endl;
// can't work!
const char * szData1 = oss.str().c_str();
// work!
std::string ss = oss.str();
const char * szData2 = ss.c_str();
例子:
用std::ostringstream获取整个文件的内容:
ifstream ifs(
"
in.txt
"
);
istream_iterator < char > inpos(ifs);
istream_iterator < char > endpos;
ostream_iterator < char > out (oss);
std::copy(inpos, endpos, out );
// 有些情况下需要取得buffer:
std::string ss = oss.str();
const char * szData = ss.c_str();
istream_iterator < char > inpos(ifs);
istream_iterator < char > endpos;
ostream_iterator < char > out (oss);
std::copy(inpos, endpos, out );
// 有些情况下需要取得buffer:
std::string ss = oss.str();
const char * szData = ss.c_str();