推荐使用std::stoi进行字符串转整数,它安全且易于使用;也可选Stringstream兼容旧环境,atoi简单但不安全,from_chars高性能但需c++17支持。

在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:进制,默认为十进制
示例代码:
#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 语言标准库,定义在
示例代码:
#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,注重安全性和可读性;老项目可用 stringstream 或 atoi;高性能服务可考虑 from_chars。注意处理异常或错误状态,避免程序崩溃。