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

C++ int 轉 string 的三種常用方法

     編輯:關於C++

方法一:sprintf + C 風格字符串


#include <iostream>
#include <string>
using namespace std;

int main() {
    int n = 65535;
    char buf[256];
    string s;

    sprintf(buf, "%d", n);  // 格式化寫入字符數組
    s = buf;                // 隱式構造 string
    cout << s << endl;

    return 0;
}

優點:簡單直觀,兼容 C;缺點:需預分配緩衝區,有緩衝區溢出風險(建議用 snprintf)。

方法二:strstream(已棄用)


#include <iostream>
#include <string>
#include <strstream>  // 非標準,C++98 棄用,C++11 移除
using namespace std;

int main() {
    int n = 65535;
    strstream ss;
    string s;
    ss << n;
    ss >> s;  // 從流提取到 string
    cout << s << endl;
    return 0;
}

注意:<strstream> 已從標準庫移除,**不推薦在新代碼中使用**。

方法三:std::stringstream(標準推薦)


#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main() {
    int n = 65535;
    stringstream ss;
    ss << n;
    string s = ss.str();  // 直接獲取字符串
    cout << s << endl;
    return 0;
}

優點:類型安全、無緩衝區溢出風險、支持流操作符鏈式調用、標準 C++98 起可用。

方法四:C++11 std::to_string(最簡潔)


#include <string>
#include <iostream>
using namespace std;

int main() {
    int n = 65535;
    string s = to_string(n);  // 一行搞定
    cout << s << endl;
    return 0;
}

適用場景:僅需簡單數值轉字符串,無格式化需求時首選。

性能對比(參考)

方法相對耗時備註
to_string1.0x內部實現通常優化過
stringstream1.5~2.0x流對象構建/析構開銷
sprintf0.8~1.2x最接近底層,但需手動管理緩衝區
charconv (C++17)0.5~0.8x無區域感知、無異常、最高性能

最佳實踐建議

  1. **C++11+ 一般情況**:直接用 std::to_string
  2. **需要格式控制**(進制、寬度、填充):用 std::stringstream 或 fmt::format (C++20 std::format)
  3. **極致性能/嵌入式**:C++17 std::to_chars (<charconv>) 無分配、無異常、最快
  4. **避免使用**:strstream、itoa (非標準)、sprintf 無長度檢查版本
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved