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