C++中string转int常用方法有三种:①std::stoi,简单直接但需处理异常;②std::stringstream,兼容性好可精确控制解析过程;③std::from_chars(C++17),无异常高性能适合性能敏感场景。

在C++中,将std::string转换为int类型有多种方法,常用且安全的方式包括使用std::stoi、std::stringstream以及std::from_chars(C++17起)。下面介绍这些实现方式及其使用场景。
使用 std::stoi 转换 string 到 int
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;
}
注意:当字符串格式不合法或数值超出int表示范围时,std::stoi会抛出异常,需用try-catch处理。
立即学习“C++免费学习笔记(深入)”;
使用 stringstream 转换
利用std::stringstream进行类型转换,适合需要兼容旧标准或复杂输入解析的场景。
#include
#include
#include
int main() {
std::string str = "6789";
std::stringstream ss(str);
int num;
if (ss >> num && ss.eof()) {
std::cout << "转换成功: " << num << std::endl;
} else {
std::cerr << "转换失败:字符串格式无效" << std::endl;
}
return 0;
}
说明:ss.eof() 确保整个字符串都被读取,防止如 "123abc" 这类部分匹配的情况被误判为成功。
使用 std::from_chars(C++17)
这是C++17引入的高效无异常方法,适用于对性能要求较高的场合。
#include
#include
#include
int main() {
std::string str = "42";
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;
}
优点:不抛异常、速度快、可指定进制(如二进制、十六进制),适合嵌入式或高性能应用。
基本上就这些常用方法。根据项目需求选择:简单场景用std::stoi,需控制异常时用stringstream,追求性能且支持C++17以上推荐std::from_chars。注意始终验证输入合法性,避免运行时错误。











