目录
一、atoi了解使用
首先我们对atoi有个简单的认识
atoi函数是用来将字符串转换整数(int)
atoi函数头文件
#include<stdlib.h>
atoi函数声明
int atoi(const char *str)
atoi使用例
#include<stdio.h>
#include<stdlib.h>
int main()
{
char a[200] = "-123456asd";
char b[200] = "123456";
char c[200] = "-12345";
char d[200] = "-123asd123";
int ret1 = atoi(a);
int ret2 = atoi(b);
int ret3 = atoi(c);
int ret4 = atoi(d);
printf("%d\n%d\n%d\n%d", ret1, ret2, ret3, ret4);
return 0;
}
运行结果:
二、atoi函数模拟
考虑条件
(1)空指针
(2)空字符串
(3)空格
(4)+-
(5)越界
(6)费数字字符
模拟atoi代码实现
可以看代码注释,基本详细解释,这里就不拿出来解释啦
#include<stdio.h>
#include<assert.h> // assert
#include<ctype.h> // isspace 、 isdigit
#include<limits.h> // 使用 INT_MAX、INT_MIN
enum Status //一个枚举变量用来判断
{
VALID, //0
INVALID //1
}sta=INVALID; //默认为非法值
int my_atoi(const char* str)
{
int flag = 1;
assert(str);
if (*str == '\0') //空字符串直接返回0
return 0;
while (isspace(*str))
{
str++;//跳过空白字符
}
if (*str == '+')
{
flag = 1; //正号就是正值,标记为1
str++;
}
else if (*str == '-')
{
flag = -1; //负号赋负值,标记-1
str++;
}
long long ret = 0; //可以大过整型
while (*str) //不等于\0时,继续进行
{
if (isdigit(*str))//检测是否是数字
{
ret = ret * 10 + flag*(*str - '0');
if (ret > INT_MAX || ret < INT_MIN) //检测越界
{
return 0; //都已经打过整型,越界不用返回值
}
}
else//如果不是直接返回,就是非法转化
{
return ret;
}
str++;
}
if (*str == '\0') //如果是走全部流程的走到\0,确认为合法
{
sta == VALID;
}
return (int )ret;
}
int main()
{
char d[200] = "-123asd123";
int ret4 = my_atoi(d);
if (sta == INVALID)
{
printf("非法转化:%d\n",ret4);
}
else if(sta==VALID)
{
printf("合法转换:\n",ret4);
}
return 0;
}