首页 > 后端开发 > C++ > 正文

C++如何将字符串转换为整数_C++ string转int方法详解与实例

冰火之心
发布: 2025-12-08 14:12:33
原创
894人浏览过
推荐使用std::stoi进行字符串转整数,它安全且易于使用;也可选stringstream兼容旧环境,atoi简单但不安全,from_chars高性能但需C++17支持。

c++如何将字符串转换为整数_c++ string转int方法详解与实例

在C++中,将字符串(std::string)转换为整数(int)是常见的操作。根据不同的需求和环境,有多种方法可以实现这一功能。本文将详细介绍几种常用且可靠的方法,并提供实际代码示例。

使用 std::stoi() 函数(推荐)

std::stoi() 是 C++11 引入的标准库函数,用于将字符串转换为整数。它定义在 头文件中,使用简单且功能强大。

语法:

int stoi(const string& str, size_t* pos = 0, int base = 10);

立即学习C++免费学习笔记(深入)”;

  • str:要转换的字符串
  • pos:可选参数,记录转换结束的位置
  • base:进制,默认为十进制

示例代码:

一览妙笔
一览妙笔

自媒体、编剧、营销人员写作工具

一览妙笔 50
查看详情 一览妙笔
#include <iostream>
#include <string>
using namespace std;
<p>int main() {
string str = "12345";
try {
int num = stoi(str);
cout << "转换结果:" << num << endl;
} catch (const invalid_argument& e) {
cout << "无效参数:" << e.what() << endl;
} catch (const out_of_range& e) {
cout << "数值超出范围:" << e.what() << endl;
}
return 0;
}
登录后复制

注意:如果字符串无法转换或数值超出 int 范围,stoi() 会抛出异常,建议用 try-catch 包裹。

使用 stringstream

stringstream 是基于流的转换方式,适用于需要格式化输入输出的场景,兼容性好,适合老版本编译器。

示例代码:

#include <iostream>
#include <sstream>
#include <string>
using namespace std;
<p>int main() {
string str = "67890";
int num;
stringstream ss(str);</p><pre class="brush:php;toolbar:false;">if (ss >> num) {
    cout << "转换成功:" << num << endl;
} else {
    cout << "转换失败" << endl;
}
return 0;
登录后复制

}

这种方法不会抛出异常,可通过判断流状态来检查是否转换成功。

使用 atoi() 函数(C 风格)

atoi() 来自 C 语言标准库,定义在 中。它接受 const char* 类型,因此需调用 c_str() 方法。

示例代码:

#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
<p>int main() {
string str = "42";
int num = atoi(str.c_str());
cout << "转换结果:" << num << endl;
return 0;
}
登录后复制

优点是简单直接,但缺点是遇到非法字符时返回 0,无法区分“转换失败”和“原值就是 0”,且不抛出异常,安全性较低。

使用 std::from_chars(C++17 起,高性能)

如果你使用的是 C++17 或更高版本,std::from_chars 是更高效、无异常的方式,定义在 头文件中。

示例代码:

#include <iostream>
#include <string>
#include <charconv>
#include <array>
using namespace std;
<p>int main() {
string str = "54321";
int num;
const auto result = from_chars(str.data(), str.data() + str.size(), num);</p><pre class="brush:php;toolbar:false;">if (result.ec == errc()) {
    cout << "转换成功:" << num << endl;
} else {
    cout << "转换失败" << endl;
}
return 0;
登录后复制

}

该方法性能高,适用于对性能敏感的场景,但语法略复杂,且要求编译器支持 C++17。

基本上就这些。选择哪种方法取决于你的项目环境和需求:日常开发推荐 std::stoi,注重安全性和可读性;老项目可用 stringstreamatoi;高性能服务可考虑 from_chars。注意处理异常或错误状态,避免程序崩溃。

以上就是C++如何将字符串转换为整数_C++ string转int方法详解与实例的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号