String to Integer (atoi) C++实现

本文详细介绍了如何实现字符串到整数的转换函数atoi。通过具体步骤和C++代码示例,阐述了如何处理输入字符串中的空白字符、正负号以及数字字符,确保函数能够正确地将字符串转换为整数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题详见:String to Integer (atoi)

将函数atoi实现出来。题目描述如下:
Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.

Requirements for atoi:
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

解题思路:

      实现atoi函数的算法看似简单,不过是将字符串中的一串数字转为一个整数,但是其苛刻的要求使得实现起来要考虑的东西比较多,也因此WA了很多次。该函数的要求有:
      1.该函数首先丢弃尽可能多的空格字符,直到找到第一个非空格字符。然后,从该字符开始,选择一个可选的初始正号或负号,后跟尽可能多的数字,并将其解释为数值。
      2.该字符串可以包含形成整数之后的其他字符,这些字符将被忽略,并且不影响此函数的行为。也就是说一旦在选定了正负号以后如果在向后查找过程中遇到非数字字符即为判定的数字串的结束条件。
      3.如果str中的第一个非空白字符序列不是有效的整数,或者由于str为空或仅包含空格字符,否则不存在此类序列,则不进行转换。
      4.如果不能执行有效的转换,则返回零值。如果正确的值超出可表示值的范围,则返回INT_MAX(2147483647)或INT_MIN(-2147483648)。
      具体的C++实现算法如下:

class Solution {
public:
    int myAtoi(string str) {
        long ans=0;
        bool tag=true;
        for(int i=0;i<str.length();){
            while(str[i]==' ') ++i;
            if(str[i]=='-'||str[i]=='+'){
                tag=(str[i]=='-')?false:true;
                ++i;
            }
            while(str[i]>='0'&&str[i]<='9'){
                ans=ans*10+(str[i]-'0');
                if(tag&&ans>=INT_MAX)    return INT_MAX;
                if(!tag&&-ans<=INT_MIN)    return INT_MIN;
                ++i;
            }
            return (tag?ans:-ans);
        }
        return (tag?ans:-ans);
    }
};

上述算法提交运行结果如下:
atoi

### C++ 中 `atoi` 函数的用法 #### 定义与功能 `atoi` 是一个标准库函数,用于将字符串转换成整数。该函数位于 `<cstdlib>` 头文件中[^3]。 #### 声明方式 ```cpp int atoi(const char *str); ``` 此声明表明 `atoi` 接受一个指向字符数组(即字符串)的指针作为输入,并返回一个整数值[^3]。 #### 使用示例 下面是一些关于如何使用 `atoi` 的例子: ```cpp #include <iostream> #include <cstdlib> // 包含 atoi 所需头文件 using namespace std; void demonstrateAtoi() { const char* str1 = "123"; int num1 = atoi(str1); cout << "String to integer conversion of : " << str1 << endl; cout << "Integer: " << num1 << endl; const char* str2 = "-789"; int num2 = atoi(str2); cout << "String to integer conversion of : " << str2 << endl; cout << "Integer: " << num2 << endl; const char* str3 = "abc"; int num3 = atoi(str3); cout << "String to integer conversion of : " << str3 << endl; cout << "Integer: " << num3 << endl; // 当无法解析有效整数时,默认返回0 } ``` 上述代码展示了三种不同类型的字符串被传递给 `atoi()` 后的结果——正整数、负整数以及非数字串。对于最后一个案例,由于传入的是非法格式的数据,“abc”,因此得到的结果是默认值 0[^3]。 #### 错误处理 需要注意的是,在遇到第一个不是构成合法整数序列的部分之前,`atoi` 不会停止读取;如果整个字符串都不是有效的,则返回零而不是抛出异常或错误提示。所以在实际应用中应当谨慎对待可能存在的无效数据情况并考虑加入额外验证逻辑来增强程序健壮性[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值