#include <stdlib.h>
//
//空指针
//""
//空白字符
//+/-
//溢出
//
#include <assert.h>
#include <ctype.h>
enum State
{
VALID,//合法的
INVALID//不合法的
}state = INVALID;//默认表示非法
int my_atoi(const char* str)
{
assert(str);
if (*str == '\0')
{
return 0;
}
//跳过空白字符
while (isspace(*str))
{
str++;
}
int flag = 1;
if (*str == '+')
{
str++;
}
else if (*str == '-')
{
flag = -1;
str++;
}
long long ret = 0;
while (*str)
{
if (isdigit(*str))//判断是不是数字字符
{
ret = ret * 10 + flag * (*str - '0');//减去字符0,转化为数字
if (ret > INT_MAX)
{
return INT_MAX;
}
else if (ret < INT_MIN)
{
return INT_MIN;
}
}
else//不是数字的情况
{
return (int)ret;
}
str++;
}
state = VALID;
return (int)ret;
}
int main()
{
int ret = my_atoi("123411111111111111115");
if (state == VALID)
printf("%d\n", ret);
else
printf("非法字符串转换,%d\n", ret);
return 0;
}
//isdigit()
原文链接:C 库函数 – isdigit() | 菜鸟教程 (runoob.com)
//isspace()