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;
}