1.atoi函数的介绍
此函数的功能是将数字字符的字符串转化为字面上的整型返回,
例如
char arr[] = "1234";
将”1234“ -> 1234(int)
#include <assert.h>
#include <ctype.h>
#include <limits.h>
enum State
{
INVALID,//0
VALID //1
};
//state 记录的是my_atoi 返回的值是合法转化的值,还是非法的状态
enum State state = INVALID;
int my_atoi(const char* s)
{
int flag = 1;
//assert(NULL != s);
//
//空指针
if (NULL == s)
{
return 0;
}
//空字符
if (*s == '\0')
{
return 0;
}
//跳过空白字符
while (isspace(*s))
{
s++;
}
//+/-
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
{
state = VALID;
//非数字字符的情况
return (int)n;
}
}
int main()
{
//1. 空指针
//2. 空字符串
//3. 遇到了非数字字符
//4. 超出范围
//const char* p = "-123111111111111111111111111111111111111";
//"0"
//int ret = my_atoi(p);
const char* p = " -123a";
int ret = my_atoi(p);
if (state == VALID)
printf("正常的转换:%d\n", ret);
else
printf("非法的转换:%d\n", ret);
return 0;
}