atoi函数的作用是将一个字符串中的数字变成整型的数字
#include<stdlib.h>
#include<assert.h>
#include<ctype.h>
#include<limits.h>
enum State
{
INVALID,
VALID
};
enum State state = INVALID;
int my_atoi(const char* s)
{
if (NULL == s)
{
return 0;
}
if (*s == '\0')
{
return 0;
}
while (isspace(*s))
{
s++;
}
int flag = 1;
if (*s == '+')
{
flag = 1;
s++;
}
else if (*s == '-')
{
flag = -1;
s++;
}
long long n = 0;
while (isdigit(*s))
{
n = n * 10 + flag * (*s - '0');
if (n > INT_MAX || n < INT_MIN)
{
return 0;
}
s++;
}
if (*s == '\0')
{
state = VALID;
return (int)n;
}
else
{
return (int)n;
}
}
int main()
{
char* p = "1234";
int ret = my_atoi(p);
if (state == VALID)
{
printf("正常转换:%d\n", ret);
}
else
{
printf("非法转换:%d\n", ret);
}
return 0;
}