首页 > 编程语言 > 详细

c语言:模拟实现库函数的atoi函数,将字符串转换成整数

时间:2016-03-03 06:51:54      阅读:295      评论:0      收藏:0      [点我收藏+]

//  模拟实现库函数的atoi函数

程序:

#include <stdio.h>

#include <string.h>

#include <assert.h>

#include <ctype.h>//isspace判断字符是否为空白字符


int my_atoi(char const *p)

{

int ret = 0;

int a = 0;

int flag = 1;

assert(p != NULL);

while (isspace(*p))

{

p++;

}

while (*p)

{

if (*p == ‘+‘)

p++;

else if (*p == ‘-‘)

{

p++;

flag = -1;

}

else if (*p >= ‘0‘&& *p <= ‘9‘)

{

a = *p - ‘0‘;

ret = (ret * 10 + a);

p++;

}

else

return 0;

}

if ((flag == 1 && ret > 0x7FFFFFFF) || (flag == -1 && ret < (signed int)0x80000000))

return 0;

return ret*flag;

}


int main()

{

printf("%d\n", my_atoi(" +2345"));

printf("%d\n", my_atoi(" -2345"));

printf("%d\n", my_atoi("+2345"));

printf("%d\n", my_atoi("-2345"));

printf("%d\n", my_atoi("2345"));

printf("%d\n", my_atoi(""));

printf("%d\n", my_atoi("xiaoxiao"));

return 0;

}

结果:

2345

-2345

2345

-2345

2345

0

0

请按任意键继续. . .


本文出自 “岩枭” 博客,请务必保留此出处http://yaoyaolx.blog.51cto.com/10732111/1746948

c语言:模拟实现库函数的atoi函数,将字符串转换成整数

原文:http://yaoyaolx.blog.51cto.com/10732111/1746948

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!