库函数atoi介绍 :
作用:将字符串中的数字转换成整形数字
参数:字符串指针
返回类型:int整形
模拟实现代码如下:
#define _CRT_SECURE_NO_WARNINGS 1
// 模拟实现库函数atoi
#include <stdio.h>
#include <assert.h>
#include <ctype.h>
#include <limits.h>
enum State
{
VALID,
INVILID
};
enum State state = INVILID;
int my_atoi(const char* str)
{
// str是空指针
assert(str);
//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; //判断数字是否越界(int)
while (*str)
{
if (isdigit(*str))
{
ret = ret * 10 + flag*(*str - '0');
if (ret > INT_MAX || ret < INT_MIN)
{
return 0; //异常返回
}
str++; //遇到\0停止
}
else
{
state = VALID;
return (int)ret;
}
}
state = VALID;
return (int)ret;
}
int main()
{
int ret=my_atoi(" -1234aa");
if (state == VALID)
{
printf("合法返回,值为:%d\n", ret);
}
else
{
printf("异常返回,值为:%d\n", ret);
}
return 0;
}