库函数atoi c语言实现

库函数原型:

#inclue <stdlib.h>

int atoi(const char *nptr);

用法:将字符串里的数字字符转化为整形数,返回整形值。

注意:转化时跳过前面的空格字符,直到遇上数字或正负符号才开始做转换,而再遇到非数字或字符串结束符号时('/0')才结束转换,并将结果返回

例:

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

int main()
{

    char *ptr1 = "-12345.12";
    char *ptr2 = "+1234w34";
    char *ptr3 = "   456er12";
    char *ptr4 = "789 123";
    int a,b,c,d;

    a = atoi(ptr1);
    b = atoi(ptr2);

    c = atoi(ptr3);
    d = atoi(ptr4);

    printf("a = %d, b = %d, c = %d, d = %d/n", a,b,c,d);

    return 0;
}

输出结果:a = 12345 b = 1234 c = 456 d = 789

***************************************************

不调用库函数用C语言实现atoi函数的功能:

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

int my_atoi(const char *str);

int main(int argc, char *argv[])
{

    char *ptr = " 1234 3455";
    int n;

    n = my_atoi(ptr);
    printf("myAtoi:%d/n", n);

    n = atoi(ptr);
    printf("atoi:%d/n", n);

    return 0;
}

int my_atoi(const char *str)
{

    int value = 0;
    int flag = 1; //判断符号

    while (*str == ' ')  //跳过字符串前面的空格
    {

        str++;
    }

    if (*str == '-')  //第一个字符若是‘-’,说明可能是负数
    {

        flag = 0;
        str++;
    }
    else if (*str == '+') //第一个字符若是‘+’,说明可能是正数

    {

        flag = 1;
        str++;
    }//第一个字符若不是‘+’‘-’也不是数字字符,直接返回0

    else if (*str >= '9' || *str <= '0')
 
    {
        return 0;    
    }

    //当遇到非数字字符或遇到‘/0’时,结束转化
    while (*str != '/0' && *str <= '9' && *str >= '0')

    {
        value = value * 10 + *str - '0'; //将数字字符转为对应的整形数

        str++;

    }

    if (flag == 0) //负数的情况
    {

        value = -value;
    }

    return value;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值