C++ string转int详解_C++字符串转整数的几种方式

答案:C++中字符串转整数常用方法有std::stoi(简洁但需异常处理)、std::stringstream(类型安全、可检测部分转换)、atoi(简单但错误难察觉)和std::from_chars(高性能、C++17推荐)。

在C++中,将字符串(std::string)转换为整数(int)是常见的操作,尤其在处理用户输入、读取配置文件或解析数据时非常实用。本文介绍几种常用且可靠的字符串转整数的方法,并说明它们的优缺点和使用场景。

1. 使用 std::stoi 函数(C++11 起)

std::stoi 是最简单直接的方式之一,定义在 头文件中,用于将字符串转换为 int 类型。

基本用法:

std::string str = "123";
int num = std::stoi(str);

优点:

  • 语法简洁,易于使用
  • 支持十进制、十六进制(加 0x 前缀)、八进制(加 0 前缀)等格式
  • 可指定起始位置和进制(如二进制、八进制)

注意事项:

  • 如果字符串为空或无法转换,会抛出 std::invalid_argument 异常
  • 如果数值超出 int 范围,会抛出 std::out_of_range 异常
  • 建议使用 try-catch 捕获异常以增强健壮性
try {
    int num = std::stoi("abc");
} catch (const std::invalid_argument& e) {
    std::cout } catch (const std::out_of_range& e) {
    std::cout }

2. 使用 std::stringstream

stringstream 是传统而灵活的方法,适用于需要类型安全转换或与其他类型混合处理的场景。

基本用法:

#include

std::string str = "456";
std::stringstream ss(str);
int num;
ss >> num;

优点:

  • 类型安全,不会自动忽略非法字符
  • 可以结合判断流状态来检测转换是否成功
  • 适合复杂格式解析(如提取多个值)

检查转换是否成功:

if (ss.fail()) {
    std::cout } else if (!ss.eof()) {
    std::cout }

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

atoi 来自 C 语言标准库,声明在 中,接受 const char* 类型。

基本用法:

std::string str = "789";
int num = std::atoi(str.c_str());

优点:

  • 简单快捷,无需异常处理
  • 兼容性好,适用于老项目

缺点:

  • 遇到非法字符时返回 0,无法区分 “0” 和错误情况
  • 不抛出异常,错误难以察觉
  • 不推荐在新代码中使用,除非对性能要求极高且输入可控

4. 使用 std::from_chars(C++17 起)

std::from_chars 是 C++17 引入的高性能无异常方法,位于 头文件中。

基本用法:

#include
#include

std::string str = "1234";
int num;
auto result = std::from_chars(str.data(), str.data() + str.size(), num);

if (result.ec == std::errc()) {
    std::cout } else {
    std::cout }

优点:

  • 零开销,不抛异常,性能极高
  • 精确控制解析范围
  • 错误码机制清晰可靠

适用场景: 对性能敏感的程序,如游戏引擎、高频交易系统等。

基本上就这些常见方式。选择哪种方法取决于你的编译器支持、性能需求和错误处理策略。日常开发推荐使用 std::stoi,追求性能选 std::from_chars,维护旧代码可能遇到 atoistringstream。不复杂但容易忽略异常和边界处理。