首页 > 其他 > 详细

模拟实现atoi函数

时间:2016-01-24 19:47:45      阅读:142      评论:0      收藏:0      [点我收藏+]

atoi函数就是把一串字符串转换为int型整数的函数,通过将字符串中的字符一个一个强制类型转换,并且存入一个临时数组中,再将数组中的数字处理一下即可得到我们需要的整数。

实现这个函数的过程中,我们需要注意负数的处理,要进行一次判断,确定返回值的正负。

其他的字符按照ASCII码表进行转换即可。

下面是代码:

#include<stdio.h>
#include<math.h>

int my_atoi(char a[],int sz)
{
	int i = 0, count = 0, ret = 0, tcount = 0, pm = 1, sum[64];
	for (i = 0; i < sz; i++)
	{
		int tmp = (int)a[i];
		if (45 == tmp)
		{
			pm = 0;
			continue;
		}
		if (47 < tmp && 59 > tmp)
			sum[count++] = tmp - 48;
	}
	tcount = count--;
	for (i = 0; i < tcount; i++)
		ret+= (pow(10, count--))*(sum[i]);


	if (0 == pm)
		return ret*-1;
	else
		return ret;
}

int main()
{
	char a[] = "1233423144";
	int i = my_atoi(a,sizeof(a)/sizeof(a[0]));
	printf("%d\n", i);
	system("pause");
	return 0;
}


模拟实现atoi函数

原文:http://lzd1995.blog.51cto.com/10973198/1738043

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