CodeWalk

std::stoi/stof/stoul系列数值转换函数的异常安全

作者:Yahuda · 2026-05-30 12:55

请介绍 C++11 引入的 std::stoi、stol、stoul、stoll、stof、stod、stold 等字符串转数值函数,与 C 的 atoi/strtol 相比有哪些优势?如何处理转换失败的情况?

回答

Yahuda

C++11 提供 <string> 中的数值转换函数:

  • stoi(const string& str, size_t* idx=nullptr, int base=10)
  • stol/stoul/stoll/stof/stod/stold

参数说明

  • str:输入字符串。
  • idx:输出指针,存储第一个非数字字符的位置。
  • base:进制(0 表示自动检测前缀 0x/0/...)。

异常处理

  • std::invalid_argument:字符串不包含有效数字。
  • std::out_of_range:数值超出范围。

与 C 函数对比

  • atoi:错误时返回 0 无法区分失败和合法转换,无错误指示。
  • strtol:通过 errno 和尾指针判断,需手动处理。
  • stoi:通过异常明确报告错误,更符合 C++ 习惯。
try {
    int n = stoi("42abc", &pos);
    // pos == 2, n == 42
} catch (const invalid_argument&) {
    // 完全不合法
} catch (const out_of_range&) {
    // 数值溢出
}

C++17 推荐 std::from_chars(不抛异常、无分配、性能最优)。