c++中string如何转换为int_c++ string转int类型实现方法

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

c++中string如何转换为int_c++ string转int类型实现方法

在C++中,将std::string转换为int类型有多种方法,常用且安全的方式包括使用std::stoistd::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。注意始终验证输入合法性,避免运行时错误。

以上就是c++++中string如何转换为int_c++ string转int类型实现方法的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1477951.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月19日 02:29:41
下一篇 2025年12月19日 02:29:55

相关推荐

发表回复

登录后才能评论
关注微信