核心方法
#include
#include // atoi, strtol
#include // stringstream
#include // stoi, stod (C++11)
std::string s = "12345";
// 1. C++11 標準庫 (推薦)
int i = std::stoi(s); // 拋出 invalid_argument / out_of_range
long l = std::stol(s);
double d = std::stod(s);
// 2. C 風格 (不拋異常,錯誤返回 0)
int i2 = std::atoi(s.c_str());
long l2 = std::strtol(s.c_str(), nullptr, 10);
// 3. stringstream (舊標準通用)
std::stringstream ss(s);
int i3; ss >> i3;
// 運算後轉回 string
std::string result = std::to_string(i + 10); // C++11
// 或
char buf[32]; std::sprintf(buf, "%d", i + 10); std::string result2(buf);
完整封裝示例
template <typename T>
T str_to_num(const std::string& s) {
std::stringstream ss(s);
T val; ss >> val;
if (ss.fail() || !ss.eof()) throw std::runtime_error("Invalid number: " + s);
return val;
}
std::string num_to_str(auto val) { return std::to_string(val); } // C++20
// C++17: template std::string num_to_str(T val) { return std::to_string(val); }
注意事項
atoi 無錯誤檢測,"abc" 返回 0,生產環境禁用。
stoi 遇非數字拋異常,需 try-catch。
- 大數字/高精度用
boost::multiprecision::cpp_int 或 long double。