码迷,mamicode.com
首页 > 其他好文 > 详细

模拟实现atoi函数

时间:2016-01-24 19:49:32      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:c语言学习

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函数

标签:c语言学习

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!