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 起可用。
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_string | 1.0x | 內部實現通常優化過 |
stringstream | 1.5~2.0x | 流對象構建/析構開銷 |
sprintf | 0.8~1.2x | 最接近底層,但需手動管理緩衝區 |
charconv (C++17) | 0.5~0.8x | 無區域感知、無異常、最高性能 |
std::to_stringstd::stringstream 或 fmt::format (C++20 std::format)std::to_chars (<charconv>) 無分配、無異常、最快strstream、itoa (非標準)、sprintf 無長度檢查版本