05.atoi函数模拟

#include <stdlib.h>
//
//空指针
//""
//空白字符
//+/-
//溢出
//
#include <assert.h>
#include <ctype.h>

enum State
{
    VALID,//合法的
    INVALID//不合法的
}state = INVALID;//默认表示非法

int my_atoi(const char* str)
{
    assert(str);
    if (*str == '\0')
    {
        return 0;
    }
    //跳过空白字符
    while (isspace(*str))
    {
        str++;
    }
    int flag = 1;
    if (*str == '+')
    {
        str++;
    }
    else if (*str == '-')
    {
        flag = -1;
        str++;
    }
    long long ret = 0;
    while (*str)
    {
        if (isdigit(*str))//判断是不是数字字符
        {
            ret = ret * 10 + flag * (*str - '0');//减去字符0,转化为数字
            if (ret > INT_MAX)
            {
                return INT_MAX;
            }
            else if (ret < INT_MIN)
            {
                return INT_MIN;
            }
        }
        else//不是数字的情况
        {
            return (int)ret;
        }
        str++;
    }
    
    state = VALID;
    return (int)ret;
}

int main()
{
    int ret = my_atoi("123411111111111111115");

    if (state == VALID)
        printf("%d\n", ret);
    else
        printf("非法字符串转换,%d\n", ret);

    return 0;
}

//isdigit()

原文链接:C 库函数 – isdigit() | 菜鸟教程 (runoob.com)

//isspace()

原文链接:isspace 的搜索結果 (runoob.com)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值