库函数atoi的使用及模拟实现

 一、简介

在C语言中,atoi函数是一个非常实用的库函数,它可以将字符串转换为整数。这个函数的原型如下:

int atoi (const char * str);

这个函数接受一个字符串作为参数,然后返回这个字符串所表示的整数值。如果字符串不能转换为有效的整数,那么函数将返回0。 

Convert string to integer
将字符串转换为整数

Parses the C-string str interpreting its content as an integral number, which is returned as a value of type int.
解析 C 字符串 str,将其内容解释为整数,该整数作为 类型的 int 值返回。

The function first discards as many whitespace characters (as in isspace) 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 base-10 digits as possible, and interprets them as a numerical value.
该函数首先根据需要丢弃尽可能多的空格字符(如 isspace ),直到找到第一个非空格字符。然后,从这个字符开始,采用一个可选的初始加号或减号,后跟尽可能多的以 10 为基数的数字,并将它们解释为数值。

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 and zero is returned.
如果 str 中的第一个非空格字符序列不是有效的整数,或者由于 str 为空或仅包含空格字符而不存在此类序列,则不执行任何转换并返回零。

 二、参数

str

C-string beginning with the representation of an integral number.
以整数的表示形式开头的 C 字符串。

三、返回值 

On success, the function returns the converted integral number as an int value.
成功后,该函数将转换后的整数作为 int 值返回。
If the converted value would be out of the range of representable values by an int, it causes undefined behavior. See strtol for a more robust cross-platform alternative when this is a possibility.
如果转换后的值超出可表示值 int 的范围,则会导致未定义的行为。如果可能,请参阅 strtol 更强大的跨平台替代方案。

四、使用

使用时需包含如下头文件:

​#include <stdlib.h>

 示例代码:

#include <stdio.h>
#include <stdlib.h>

int main() 
{
    char str[] = "12345";
    int num = atoi(str);
    printf("The integer is %d\n", num);
    return 0;
}

输出结果:

五、模拟实现

如果你想要模拟实现atoi函数,可以参考以下代码:

int my_atoi(const char* str) 
{
    int result = 0;
    int sign = 1;

    // 跳过前导空格
    while (*str == ' ') {
        str++;
    }

    // 检查符号
    if (*str == '-' || *str == '+') {
        if (*str == '-') {
            sign = -1;
        }
        str++;
    }

    // 转换数字并防止溢出
    while (*str >= '0' && *str <= '9') {
        if (result > INT_MAX / 10 || (result == INT_MAX / 10 && *str - '0' > INT_MAX % 10)) {
            return sign == 1 ? INT_MAX : INT_MIN;
        }
        result = result * 10 + (*str - '0');
        str++;
    }

    return result * sign;
}

这个函数首先跳过字符串中的前导空格,然后检查数字的符号。

接下来,它遍历字符串中的每个字符,将每个字符转换为数字,并将这个数字加到结果中。在这个过程中,函数还需要检查结果是否会溢出。如果结果会溢出,那么函数就返回INT_MAXINT_MIN

while (*str >= '0' && *str <= '9') {
    if (result > INT_MAX / 10 || (result == INT_MAX / 10 && *str - '0' > INT_MAX % 10)) {
        return sign == 1 ? INT_MAX : INT_MIN;
    }
    result = result * 10 + (*str - '0');
    str++;
}

首先检查当前字符是否为数字字符(‘0’到’9’)。如果是,那么就进入循环。

在循环中,首先会检查result是否大于INT_MAX / 10,这是因为接下来我们要将result乘以10,如果result大于INT_MAX / 10,那么乘法运算就会导致溢出。同时,如果result等于INT_MAX / 10,我们还需要检查下一个数字是否大于INT_MAX的最后一位,如果是,那么加法运算也会导致溢出。如果上述任何一种溢出的情况发生,那么函数就会立即返回INT_MAXINT_MIN,取决于符号sign


【注】

sign == 1 ? INT_MAX : INT_MIN是C语言中条件运算符的一个例子。这个运算符的格式是condition ? expression_if_true : expression_if_false

在这个例子中,sign == 1是条件,INT_MAX是当条件为真时的表达式,INT_MIN是当条件为假时的表达式。

所以,sign == 1 ? INT_MAX : INT_MIN的意思是:如果sign等于1,那么结果就是INT_MAX,否则结果就是INT_MIN

这个表达式常常用在atoi函数的模拟实现中,用来处理整数溢出的情况。如果在转换过程中发生了溢出,那么函数就会返回INT_MAXINT_MIN,取决于sign的值。如果sign为1,表示原始字符串是正数,那么就返回INT_MAX;如果sign为-1,表示原始字符串是负数,那么就返回INT_MIN。这样就可以确保函数的返回值始终在整数的有效范围内。


如果没有溢出,那么就将当前数字字符转换为数字(通过减去字符’0’),然后加到result中。这是通过result = result * 10 + (*str - '0')实现的。这行代码实际上是将result左移一位(即乘以10),然后加上新的数字。

最后,str++将指针向前移动一位,以便处理下一个字符。

最后,函数返回结果乘以符号,得到最终的整数。

使用示例:

int main() 
{
    char str[] = "-10086";
    int num = my_atoi(str);
    printf("The integer is %d\n", num);
    return 0;
}

输出结果:

以上就是atoi函数模拟实现的全部思路。

【注】这个实现可能不会完全符合atoi函数在所有情况下的行为,但是基本思路已经提供。 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值