C++(atoi())

做梦当财神 / 2024-08-23 / 原文

目录
  • 1. 函数
    • 1.1 参数
    • 1.2 返回值
    • 1.3 注意事项
  • 2. 示例
  • 3. atoi 的局限性
  • 4. 推荐替代函数



atoi() 是 C++ 标准库中的一个函数,用于将 C 风格字符串转换为整数。atoi 是 "ASCII to Integer" 的缩写,它可以将包含数字的字符串解析为整数值。

1. 函数

int atoi(const char *str);

1.1 参数

  • str:一个 C 风格的字符串,通常是 const char* 类型,表示待转换的数字字符串。该字符串必须以 null 结尾 \0

1.2 返回值

  • 函数返回转换后的整数值。
  • 如果字符串中不包含有效的数字或字符串的开头不是数字,atoi 将返回 0

1.3 注意事项

  • atoi 不能处理超出 int 类型范围的值。如果输入的字符串表示的数字超出了 int 类型的范围,行为是未定义的。
  • atoi 不提供错误检测能力。例如,如果字符串包含非数字字符,atoi 将忽略这些字符,并从字符串的开头部分进行转换。


2. 示例

#include <iostream>
#include <cstdlib> // 包含 atoi() 函数

int main() {
    const char* str1 = "1234";
    const char* str2 = "56abc";
    const char* str3 = "abc123";
    
    int num1 = atoi(str1);  // 转换为整数 1234
    int num2 = atoi(str2);  // 转换为整数 56,遇到非数字字符后停止
    int num3 = atoi(str3);  // 转换为整数 0,开头没有数字
    
    std::cout << "num1: " << num1 << std::endl;
    std::cout << "num2: " << num2 << std::endl;
    std::cout << "num3: " << num3 << std::endl;

    return 0;
}

输出:

num1: 1234
num2: 56
num3: 0


3. atoi 的局限性

  • 没有错误处理:不能检测输入错误,比如无法区分输入的字符串不含数字与数字部分超出 int 的范围(两种情况下返回值都是 0)。
  • 性能问题atoi 无法处理空白字符、符号、或进制转换等复杂场景。


4. 推荐替代函数

C++11 标准后,atoi 常被 std::stoi 取代。std::stoi 提供了错误检测并且支持更多特性:

int num = std::stoi("123");
  • std::stoi 抛出 std::invalid_argument 异常,如果无法转换为整数,或抛出 std::out_of_range 异常,如果数字超出范围。