std::stoi最简单但需异常处理;2. stringstream兼容性好可检查完整转换;3. std::from_chars(C++17)高效无异常适合高性能场景;根据编译环境和需求选择合适方法。

在C++中,将std::string转换成int有多种方法,常用且安全的方式包括使用std::stoi、std::stringstream和std::from_chars(C++17起)。下面介绍几种实用的方法。
1. 使用 std::stoi(最简单)
这是最直接的方法,适用于大多数情况。示例代码:
立即学习“C++免费学习笔记(深入)”;
#include注意:如果字符串不是有效数字或超出int范围,#include int main() { std::string str = "123"; try { int num = std::stoi(str); std::cout << "转换结果: " << num << std::endl; } catch (const std::invalid_argument& e) { std::cerr << "错误:无法转换为整数" << std::endl; } catch (const std::out_of_range& e) { std::cerr << "错误:数值超出int范围" << std::endl; } return 0; }
std::stoi会抛出异常,建议用try-catch处理。2. 使用 stringstream
利用输入流进行类型转换,兼容性好,适合老标准。示例代码:
立即学习“C++免费学习笔记(深入)”;
#include#include #include int main() { std::string str = "456"; std::stringstream ss(str); int num;
if (ss >> num && ss.eof()) { std::cout << "转换成功: " << num << std::endl; } else { std::cerr << "转换失败" << std::endl; } return 0;} 优点是能检查是否完全转换(比如防止"123abc"被部分读取),通过
eof()判断流结束位置。3. 使用 std::from_chars(C++17,高效无异常)
这是C++17引入的高性能方法,不抛异常,适合对性能要求高的场景。示例代码:
立即学习“C++免费学习笔记(深入)”;
#include#include #include int main() { std::string str = "789"; int num; auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), num);
if (ec == std::errc()) { std::cout << "转换成功: " << num << std::endl; } else { std::cerr << "转换失败" << std::endl; } return 0;} 该方法速度快,适用于嵌入式或高频调用场景,但需要编译器支持C++17。
总结与建议
- 如果代码环境支持C++11及以上,推荐使用std::stoi,简洁易读。
- 需要兼容旧标准或更精细控制时,可用stringstream。
- 追求性能且使用C++17+,优先考虑std::from_chars。基本上就这些常用方式,选择合适的方法取决于你的项目需求和编译环境。











