linux中atoi函数的实现 值得借鉴,【转】atoi()函数的实现

atoi()函数的功能:将字符串转换成整型数;atoi()会扫描参数nptr字符串,跳过前面的空格字符,直到遇上数字或正负号才开始做转换,而再遇到非数字或字符串时('\0')才结束转化,并将结果返回(返回转换后的整型数)。

atoi()函数实现的代码:

intmy_atoi(char* pstr)

{

intRet_Integer = 0;

intInteger_sign = 1;

if(pstr == NULL)

{

printf("Pointer is NULL\n");

return0;

}

while(isspace(*pstr) == 0)

{

pstr++;

}

if(*pstr =='-')

{

Integer_sign = -1;

}

if(*pstr =='-'|| *pstr =='+')

{

pstr++;

}

while(*pstr >='0'&& *pstr <='9')

{

Ret_Integer = Ret_Integer * 10 + *pstr -'0';

pstr++;

}

Ret_Integer = Integer_sign * Ret_Integer;

returnRet_Integer;

}

int my_atoi(char* pstr)

{

int Ret_Integer = 0;

int Integer_sign = 1;

if(pstr == NULL)

{

printf("Pointer is NULL\n");

return 0;

}

while(isspace(*pstr) == 0)

{

pstr++;

}

if(*pstr == '-')

{

Integer_sign = -1;

}

if(*pstr == '-' || *pstr == '+')

{

pstr++;

}

while(*pstr >= '0' && *pstr <= '9')

{

Ret_Integer = Ret_Integer * 10 + *pstr - '0';

pstr++;

}

Ret_Integer = Integer_sign * Ret_Integer;

return Ret_Integer;

}

现在贴出运行my_atoi()的结果,定义的主函数为:int main ()

intmain()

{

chara[] ="-100";

charb[] ="456";

intc = 0;

intmy_atoi(char*);

c = atoi(a) + atoi(b);

printf("atoi(a)=%d\n",atoi(a));

printf("atoi(b)=%d\n",atoi(b));

printf("c = %d\n",c);

return0;

}

int main()

{

char a[] = "-100";

char b[] = "456";

int c = 0;

int my_atoi(char*);

c = atoi(a) + atoi(b);

printf("atoi(a)=%d\n",atoi(a));

printf("atoi(b)=%d\n",atoi(b));

printf("c = %d\n",c);

return 0;

}

运行结果:

a4c26d1e5885305701be709a3d33442f.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值