| 方向 | 推薦方法 (C++11+) | C 風格/舊標準 | 備註 |
|---|---|---|---|
| string → int/float | std::stoi/std::stod | atoi/atof | 拋出異常 vs 靜默返回 0 |
| int/float → string | std::to_string | sprintf/itoa | itoa 非標準 |
| string ↔ stream | std::ostringstream/istringstream | strstream (棄用) | 格式化控制最強 |
| string → char* | c_str() (const) | 手動 new char[] + strcpy | 生命週期綁定 string |
| char* → string | string(str) 構造 | 同上 | 自動拷貝 |
<string> 轉換函數 (C++11)// string → 數字
string s = "12345";
int i = stoi(s); // 12345
double d = stod("3.14"); // 3.14
// 異常處理
try { stoi("abc"); } catch (const invalid_argument&) { /* 非數字 */ }
catch (const out_of_range&) { /* 溢出 */ }
// 數字 → string
string s2 = to_string(42); // "42"
string s3 = to_string(3.14159); // "3.141590" (固定精度)
#include
#include
// 數字 → 格式化 string
ostringstream oss;
oss << hex << uppercase << setw(8) << setfill('0') << 255; // "000000FF"
string hexStr = oss.str();
// string → 數字 (支援進制、浮點格式)
istringstream iss("0xFF");
int val; iss >> hex >> val; // 255
#include // atoi, atof, strtol, strtod
#include // sprintf, sscanf
// string → int (注意: 僅接受 const char*)
string s = "789";
int v = atoi(s.c_str()); // 簡單但無錯誤檢查
long lv = strtol(s.c_str(), nullptr, 10); // 推薦: 有錯誤檢查、支援進制
// int → char* (需預分配緩衝區)
char buf[32];
sprintf(buf, "%d", 444); // "444"
snprintf(buf, sizeof(buf), "%d", 444); // 安全版本
string s4(buf);
string str = "hello";
const char* cstr = str.c_str(); // 僅讀,生命週期 ≤ str
// 需可修改副本:
vector writable(str.begin(), str.end());
writable.push_back('\0');
char* modifiable = writable.data();
char* cstr2 = "world";
string str2(cstr2); // 構造拷貝
to_string/stoi 分配臨時字符串,極致性能可用 char buf[32] + snprintf/fast_io 庫。stoi 拋異常,strtol 返回值 + errno/endptr 檢查,選擇項目風格統一。itoa:非標準,MSVC/部分嵌入式才有,跨平台用 sprintf 或 to_string。std::from_chars:無異常、無分配、高性能解析,首選新項目。現代 C++ 開發:數字→字符串用 to_string,字符串→數字用 stoi/stod 或 from_chars (C++17),複雜格式用 ostringstream/istringstream。理解各方法錯誤語義與性能特徵,根據場景選型。