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 是最简单直接的方法,定义在<string>头文件中,能将字符串转换为整数。
示例代码:
#include <iostream>
#include <string>
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++免费学习笔记(深入)”;
利用std::stringstream进行类型转换,适用于更复杂的解析场景,头文件为<sstream>。
示例代码:
#include <iostream>
#include <string>
#include <sstream>
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;
}
这种方法不会抛出异常,适合需要静默处理错误的场景。还可以检查是否整个字符串都被正确读取。
这是C++17引入的高效无异常方法,性能高,适用于对性能敏感的场合,定义在<charconv>头文件中。
示例代码:
#include <iostream>
#include <string>
#include <charconv>
#include <array>
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。
以上就是c++++中如何将string转换为int_C++ string转int实现方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号