string s = "1234";
int x = atoi(s.c_str()); // 需轉為 const char*
缺點:無錯誤檢測,非數字字串返回 0,溢出行為未定義。
string s = "1234";
int x = stoi(s); // 拋出 invalid_argument / out_of_range 異常
支援進制參數:stoi(s, nullptr, 16)。
string s = "1234";
int x;
stringstream ss(s);
ss >> x;
int x = 1234;
string s = to_string(x);
int x = 1234;
stringstream ss;
ss << x;
string s = ss.str();
// 注意:重用 ss 時需 ss.str("") 而非 ss.clear()
int x = 1234;
char buf[32];
sprintf(buf, "%d", x);
string s(buf);
stringstream 重用必須 ss.str("") 清空內容,ss.clear() 僅重置狀態標誌。atoi 不報錯,建議改用 strtol 或 stoi。stoll/to_string(long long)。高頻調用場景:to_string / stoi 通常最快;極致性能可用 sprintf / 手寫整數轉字符串(查表法)。