C++中string转int常用方法包括:①推荐使用C++11的stoi函数,支持自动识别进制并抛出异常处理错误;②兼容旧标准的stringstream方式,通过流操作实现安全转换;③传统atoi函数,简洁但错误处理能力弱。现代开发首选stoi配合异常处理,确保代码健壮性。

在C++中,将string类型转换为int类型是常见的操作。有多种方法可以实现这一转换,每种方法适用于不同场景,下面介绍几种常用且可靠的方式。
使用 stoi 函数(推荐)
stoi 是 C++11 引入的标准库函数,用于将字符串转换为整数,使用简单且安全。
- 函数原型定义在
头文件中。 - 支持十进制、十六进制(前缀 0x)和八进制(前缀 0)的自动识别。
- 如果字符串无法转换,会抛出
std::invalid_argument或std::out_of_range异常。
示例代码:
#include <iostream>
#include <string>
int main() {
std::string str = "12345";
try {
int num = std::stoi(str);
std::cout <h3>使用 string<a style="color:#f60; text-decoration:underline;" title="stream" href="https://m.php.cn/zt/19633.html" target="_blank">stream</a> 类</h3>
<p>利用 <code>std::stringstream</code> 可以实现类型安全的转换,适合需要兼容旧标准(C++98)的项目。</p>
<font color="#000000">
<ul>
<li>需包含头文件 <code><sstream></sstream></code>。</li>
<li>通过流操作符 <code>>></code> 提取整数值。</li>
<li>不会抛出异常,但可通过检查流状态判断是否转换成功。</li>
</ul></font><p>示例代码:</p>
<pre class="brush:php;toolbar:false;">#include <iostream>
#include <string>
#include <sstream>
int main() {
std::string str = "67890";
std::stringstream ss(str);
int num;
if (ss >> num && ss.eof()) {
std::cout <h3>使用 atoi 函数(传统方式)</h3>
<p><strong>atoi</strong> 是来自 C 语言的函数,使用简单但安全性较低。</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill13230" title="Livestream Sales Script"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20e352aa140.jpg" alt="Livestream Sales Script" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill13230" title="Livestream Sales Script" class="overflowclass">Livestream Sales Script</a>
<p class="overflowclass">直播带货脚本专家,擅长根据产品信息编写生动、吸引人且具说服力的直播脚本,突出核心卖点。</p>
</div>
<a rel="nofollow" href="/xiazai/skill13230" title="Livestream Sales Script" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>
<font color="#000000">
<ul>
<li>需包含头文件 <code><cstdlib></cstdlib></code>。</li>
<li>遇到非法字符时返回 0,无法区分“转换失败”和“实际值为0”。</li>
<li>不抛出异常,错误处理能力弱。</li>
</ul></font><p>示例代码:</p>
<pre class="brush:php;toolbar:false;">#include <iostream>
#include <string>
#include <cstdlib>
int main() {
std::string str = "42";
int num = std::atoi(str.c_str());
std::cout <h3>其他变体函数</h3>
<p>C++ 还提供了针对不同整数类型的转换函数:</p>
<font color="#000000">
<ul>
<li>
<code>std::stol</code>:转换为 long</li>
<li>
<code>std::stoul</code>:转换为 unsigned long</li>
<li>
<code>std::stoll</code>:转换为 long long</li>
<li>
<code>std::stoull</code>:转换为 unsigned long long</li>
</ul></font><p>这些函数用法与 <code>stoi</code> 相同,根据数值范围选择合适函数可避免溢出问题。</p>
<p>基本上就这些。对于现代 C++ 开发,优先使用 <strong>stoi</strong> 并配合异常处理,能写出更清晰、健壮的代码。如果项目要求兼容老编译器,<strong>stringstream</strong> 是不错的替代方案。而 <strong>atoi</strong> 虽然方便,但在关键逻辑中应谨慎使用。</p></cstdlib></string></iostream>
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!










