#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
enum
{
INVALUE,
VALUE
};
int my_atoi(char *str)
{
int tmp = 0;
int flag = 1;
int num = 0;
//空指针
assert(str != NULL);
//空字符串
if (*str == '\0')
{
return 0;
}
//空格处理
while (isspace(*str))
{
str++;
}
//+ -
if (*str == '-')
{
str++;
flag = -1;
}
//异常字符处理
while (isdigit(*str))
{
tmp = tmp * 10 + (*str -'0')*flag;
str++;
//溢出处理
if ((tmp > INT_MAX) || (tmp < INT_MIN))
{
num = INVALUE;
}
else
{
num = VALUE;
}
}
return tmp;
}
int main()
{
int a = my_atoi("");
int b = my_atoi(" ");
int c = my_atoi("1234");
int d = my_atoi("-1234");
int e = my_atoi(" 1234");
int f = my_atoi("iii1234");
int g = my_atoi("122344443433232323234");
int h = my_atoi("-12333333333333333333");
printf("%d\n", a);
printf("%d\n", b);
printf("%d\n", c);
printf("%d\n", d);
printf("%d\n", e);
printf("%d\n", f);
printf("%d\n", g);
printf("%d\n", h);
system("pause:");
return 0;
}
输出结果: