自己写的atoi实现,可能有地方没有想到,暂时写这么多,做个笔录,以备忘记。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define M 100
int fun_atoi(char str[])
{
int sum=0,i=0,len=0;
int flag=0,ret=0;
len = strlen(str);
if (str[0] == '-'){
flag = 1;
i++;
}
while (str[i] != 0)
{
if ((str[i]>='0')&&(str[i])<='9')
i++;
else
{
printf("input error ,exit\n");
exit(0);
}
}
for (i=flag;i<len;i++)
sum = sum*10 + str[i] - '0';
if (flag == 1)
{
ret = -sum;
sum = ret;
}
return sum;
}
int main()
{
char str[M] = "";
int sum=0;
printf("Please input some numbers:");
scanf("%s",str);
sum = fun_atoi(str);
printf("sum is %d\n",sum);
return 0;
}