栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

104.my

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

104.my

【C语言】模拟实现atoi函数

可以把小写l转换为1,大写O转换为0

#include
#include
#include
#include
#include
#define N 20

int my_atoidec(const char *str)
{
    int a=0;
    int sum=0;
    while(isdigit(*str)||*str=='l'||*str=='O')
    {
        a=*str;
        if(*str=='O')
        {
            a='0';
        }
        else if(*str=='l')
        {
            a='1';
        }
        else{}
        sum=sum*10+a-'0';// 减去字符0,也就是减去0的ASCII码值48,数字字符减去‘0’就得到了该数字
        str++;
    }
    return sum;
}
int my_atoihex(const char *str)
{
        int sum=0;
    while(isxdigit(*str))
    {
        int ch=0;
        if(isdigit(*str))
        {
            ch=*str-'0';
        }
        else
        {
            ch=tolower(*str)-'a'+10;
        }
        sum=sum*16+ch;
        str++;
    }
    return sum;
}
int my_atoioct(const char *str)
{
    int sum=0;
    while(isdigit(*str)&&*str!='8'&&*str!='9')
    {
        sum=sum*8+*str-'0';
        str++;
    }
    return sum;
}

int my_atoi(const char *str)
{
    int sum=0;
    assert(str!=nullptr);
    int tag=0;// 1负数,0正数
    while(isspace(*str))
    {
        str++;//跳过空白符
    }
    if(*str=='-')
    {
        tag=1;
        str++;
    }
    else if(*str=='+')
    {
        tag=0;
        str++;
    }
    if(*str=='0')
    {
        if(*(str+1)=='x'||*(str+1)=='X')
        {
            sum=my_atoihex(str+2);
        }
        else{
            sum=my_atoioct(str+1);
        }
    }
    else{
        sum=my_atoidec(str);
    }
    if(tag)
    {
        sum=-sum;
    }
    return sum;
}

int main()
{
    const char *str[]=
    {
        "12lO43",
        "12.43",
        "+12.45",
        "-12.45",
        "0123  425898",
        "0x123afbx",
        "-078",
        "qef2132",
    };
    int n=sizeof(str)/sizeof(str[0]);
    for(int i=0;i %dn",str[i],my_atoi(str[i]));
    }


	return 0;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/960858.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号