C++中string转int常用方法有三种:①std::stoi(需处理异常)②std::stringstream(无异常,可校验完整性)③std::from_chars(C++17,高性能无异常),根据标准版本与需求选择。

在C++中,将string转换为int有多种方法,常用且安全的方式包括使用std::stoi、std::stringstream和std::from_chars(C++17起)。下面分别介绍这些实现方式。
使用 std::stoi
std::stoi 是最简单直接的方法,定义在头文件中,能将字符串转换为整数。
示例代码:
#include#include int main() { std::string str = "12345"; 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处理。
立即学习“C++免费学习笔记(深入)”;
使用 stringstream
利用std::stringstream进行类型转换,适用于更复杂的解析场景,头文件为。
示例代码:
#include#include #include int main() { std::string str = "67890"; std::stringstream ss(str); int num; if (ss >> num) { std::cout << "转换成功: " << num << std::endl; } else { std::cerr << "转换失败" << std::endl; } return 0; }
这种方法不会抛出异常,适合需要静默处理错误的场景。还可以检查是否整个字符串都被正确读取。
使用 std::from_chars(C++17)
这是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::cerr << "转换失败" << std::endl; } return 0; }
std::from_chars不依赖异常,返回一个结果结构体,通过判断ec成员确定是否成功。
基本上就这些常用方法。选择哪种取决于你的C++标准版本和对异常、性能的需求。日常开发中std::stoi最方便,性能关键场景推荐std::from_chars。











