模拟atoi函数

本文介绍了C语言中用于字符串转整数的atoi函数,包括其头文件、声明及使用示例。同时,通过一个详细的代码实现过程,展示了如何模拟atoi函数,考虑了空指针、空字符串、符号、越界等条件,确保了转换的正确性和边界情况的处理。此外,还提供了一个实际应用示例来验证模拟函数的合法性。

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

目录

一、atoi了解使用

atoi函数头文件

atoi函数声明

 atoi使用例

 二、atoi函数模拟

考虑条件

模拟atoi代码实现 


一、atoi了解使用

首先我们对atoi有个简单的认识

atoi函数是用来将字符串转换整数(int)

atoi函数头文件

#include<stdlib.h>

atoi函数声明

int atoi(const char *str) 

 atoi使用例

#include<stdio.h>
#include<stdlib.h>
int main()
{
    char a[200] = "-123456asd";
    char b[200] = "123456";
    char c[200] = "-12345";
    char d[200] = "-123asd123";
    int ret1 = atoi(a);
    int ret2 = atoi(b);
    int ret3 = atoi(c);
    int ret4 = atoi(d);
    printf("%d\n%d\n%d\n%d", ret1, ret2, ret3, ret4);
    return 0;
}

运行结果:


 

 二、atoi函数模拟

考虑条件

(1)空指针

(2)空字符串

(3)空格

(4)+-

(5)越界

(6)费数字字符

模拟atoi代码实现 

可以看代码注释,基本详细解释,这里就不拿出来解释啦

#include<stdio.h>
#include<assert.h>   //  assert
#include<ctype.h>   //  isspace    、    isdigit
#include<limits.h> // 使用 INT_MAX、INT_MIN
enum Status   //一个枚举变量用来判断
{
    VALID,     //0
    INVALID    //1
}sta=INVALID;  //默认为非法值
int my_atoi(const char* str)
{
    int flag = 1;
    assert(str);
    if (*str == '\0')   //空字符串直接返回0
        return 0;
    while (isspace(*str)) 
    {
        str++;//跳过空白字符
    }
    if (*str == '+')
    {
        flag = 1;   //正号就是正值,标记为1
        str++;
    }
    else if (*str == '-')
    {
        flag = -1;   //负号赋负值,标记-1
        str++;
    }
    long long ret = 0;  //可以大过整型
    while (*str)    //不等于\0时,继续进行
    {
        if (isdigit(*str))//检测是否是数字
        {
            ret = ret * 10 + flag*(*str - '0');
            if (ret > INT_MAX || ret < INT_MIN)  //检测越界
            {
                return 0;    //都已经打过整型,越界不用返回值
            }
            
        }
        else//如果不是直接返回,就是非法转化
        {
            return ret;
        }
        str++;
    }
    if (*str == '\0')   //如果是走全部流程的走到\0,确认为合法
    {
        sta == VALID;
    }
    return (int )ret;
}
int main()
{
    char d[200] = "-123asd123";
    int ret4 = my_atoi(d);
    if (sta == INVALID)
    {
        printf("非法转化:%d\n",ret4);
    }
    else if(sta==VALID)
    {
        printf("合法转换:\n",ret4);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值