std::ostringstream 是 C++ 標準庫中用於字符串格式化的流類,定義於 <sstream>。它可執行 C 風格的流輸出操作,格式化字符串,避免手動分配大緩衝區,是 sprintf 的安全替代品。

explicit ostringstream(openmode which = ios_base::out);
explicit ostringstream(const string& str, openmode which = ios_base::out);
當需要格式化字符串但無法預知所需緩衝區大小時,ostringstream 能自動管理內存,動態擴展,且內存管理安全可靠。獲取內容使用 str() 或 str(string&) 成員函數。
std::ostringstream::str() 返回臨時 std::string 對象,不能直接對其返回值操作。錯誤示例:
const char *pBuffer = oss.str().c_str(); // 錯誤!臨時對象已析構,pBuffer 成懸空指針
正確做法:
std::string temp = oss.str();
const char *pBuffer = temp.c_str(); // 正確,temp 延長生命周期
#include <sstream>
#include <iostream>
int main() {
std::ostringstream oss;
int num = 42;
double pi = 3.14159;
oss << "Number: " << num << ", Pi: " << pi;
std::string result = oss.str();
std::cout << result << std::endl;
return 0;
}