推荐使用std::stoi转换字符串为整数,它简洁安全并支持异常处理;传统方法如stringstream兼容性好但较繁琐;atoi简单但无法区分0和转换失败;C++17的from_chars性能最佳且无异常,适合高频场景。

在C++中,将字符串(string)转换为整数(int)有多种方法,每种方式适用不同场景。下面介绍几种常用且可靠的方法,并说明其特点和使用注意事项。
1. 使用 std::stoi 函数(推荐)
std::stoi 是 C++11 引入的便捷函数,专门用于将字符串转为整数,用法简单直观。
示例代码:#include#include int main() { std::string str = "12345"; int num = std::stoi(str); std::cout << num << std::endl; // 输出 12345 return 0; }
优点:语法简洁,自动忽略前后空白字符(直到遇到有效数字),支持正负号。
注意:如果字符串内容不是合法数字(如"abc"或空字符串),会抛出 std::invalid_argument 异常;若数值超出 int 范围,则抛出 std::out_of_range。建议配合 try-catch 使用:
立即学习“C++免费学习笔记(深入)”;
try {
int num = std::stoi("not_a_number");
} catch (const std::invalid_argument& e) {
std::cout << "无效参数" << std::endl;
} catch (const std::out_of_range& e) {
std::cout << "数值超出范围" << std::endl;
}
2. 使用 stringstream
通过 std::stringstream 进行类型转换,是较传统但兼容性好的方式,适用于早期 C++ 标准。
示例代码:#include#include #include int main() { std::string str = "6789"; std::stringstream ss(str); int num; if (ss >> num) { std::cout << num << std::endl; } else { std::cout << "转换失败" << std::endl; } return 0; }
优点:可检查转换是否成功,适合处理混合字符串(如提取数字部分)。
缺点:相对繁琐,性能略低。
3. 使用 atoi 函数(C 风格,慎用)
atoi 来自 C 语言标准库,需包含
#include#include #include int main() { std::string str = "42"; int num = std::atoi(str.c_str()); std::cout << num << std::endl; return 0; }
优点:简单快速。
缺点:遇到非法输入时返回 0,无法区分“转换失败”和“原值就是0”,缺乏错误提示。不推荐在需要健壮性的程序中使用。
4. 使用 std::from_chars(C++17 起,高性能选择)
这是最现代、最高效的方式,属于头文件
#include#include #include #include int main() { std::string str = "54321"; int num; auto result = std::from_chars(str.data(), str.data() + str.size(), num);
if (result.ec == std::errc()) { std::cout << num << std::endl; } else { std::cout << "转换失败" << std::endl; } return 0;}
优点:无异常、无内存分配,性能极佳。
缺点:语法稍复杂,仅支持 C++17 及以上版本。
基本上就这些常用方法。日常开发推荐优先使用 std::stoi,兼顾简洁与安全;对性能要求高时考虑 std::from_chars;老项目兼容可用 stringstream 或 atoi,但注意错误处理。











