【C】库函数之 atoi

目录

1. Convert string to integer

2. 算法分析

3. 源代码

4. 输出结果


1. Convert string to integer

#include <stdlib.h>
int atoi (const char * str);

Parses the C-string str interpreting its content as an integral number, which is returned as a value of type 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.

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.

上述内容是 cplusplus 对 atoi 函数的介绍。

该函数用来解析字符串 str,并将 str 指向的内容转换为 int 型整数返回。

首先该函数可能会丢弃空白字符,直到找到第一个非空白字符为止,然后从该字符开始,取一个可选的正负号,最后转换为 int 型整数即可。

需要注意的是,如果字符串 str 中包含其他字符,那么这些字符将会被忽略。

2. 算法分析

实现 atoi 的基本功能是比较简单的,但是当考虑很多特殊情况时,却不是一件容易的事情,比如考虑 指针的有效性、空字符串、空白字符、是否是数字字符、是否会溢出、返回正数还是负数。

这些情况都应该考虑到,其次,异常情况下返回 0 与正常情况下返回 0 是不一样的,这里用全局变量 state 来标记当前输入是合法还是非法。

3. 源代码

#include <stdio.h>
#include <assert.h>
#include <ctype.h>
#include <limits.h>

enum State {
    VALID,
    INVALID
};  
    
enum State state = INVALID;
    
int Atoi(const char *str) {
    assert(NULL != str);
    
    int flag = 1; // 区分是正数 还是 负数
    long long ret = 0; // 防止整型溢出
    
    if ('\0' == *str)
        return 0;
    
    while (isspace(*str)) // 跳过空白字符
        ++str;
    
    // 处理正数 和 负数
    if ('+' == *str) {
        ++str;
    } else if ('-' == *str) {
        flag = -1;
        ++str;
    }

    while ('\0' != *str) {
        // 处理数字字符
        if (isdigit(*str)) {
            ret = ret * 10 + flag * (*str - '0');
            if (ret > INT_MAX)
                return INT_MAX;
            if (ret < INT_MIN)
                return INT_MIN;
            ++str;
        } else {
            return (int)ret;
        }
    }    
         
    // 这里都是有效数据
    state = VALID;
         
    return (int)ret;
}        
         
void test() {
    char str1[] = "";
    char str2[] = "0";
    char str3[] = "-12345";
    char str4[] = "12345abc  ";
    char str5[] = "     +2345abc";
    char str6[] = "-91283472332";
    char str7[] = "21474836460";
         
    int ret = Atoi(str1);
    if (VALID == state)
        printf("%d\n", ret);
    else if (INVALID == state)
        printf("invalid: %d\n", ret);

    ret = Atoi(str2);
    if (VALID == state)
        printf("%d\n", ret);
    else if (INVALID == state)
        printf("invalid: %d\n", ret);
       
    ret = Atoi(str3);
    if (VALID == state)
        printf("%d\n", ret);
    else if (INVALID == state)
        printf("invalid: %d\n", ret);
       
    ret = Atoi(str4);
    if (VALID == state)
        printf("%d\n", ret);
    else if (INVALID == state)
        printf("invalid: %d\n", ret);
       
    ret = Atoi(str5);
    if (VALID == state)
        printf("%d\n", ret);
    else if (INVALID == state)
        printf("invalid: %d\n", ret);
       
    ret = Atoi(str6);
    if (VALID == state)
        printf("%d\n", ret);
    else if (INVALID == state)
        printf("invalid: %d\n", ret);
       
    ret = Atoi(str7);
    if (VALID == state)
        printf("%d\n", ret);
    else if (INVALID == state)
        printf("invalid: %d\n", ret);
}

int main(void) {
    test();
 
    return 0;
} 

4. 输出结果

invalid: 0
0
-12345
12345
2345
-2147483648
2147483647

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值