首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++ 中替代 sprintf 的 std::ostringstream 輸出流詳解

     編輯:關於C++

簡介

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;
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved