atoi函数模拟实现
C语言提供了一系列函数把字符串转换为整数:atoi、atol、atoll和atoq。
我们来看代码
#include,stdio.h>
#include //函数包含头文件
int main()
{
char arr1[] = "-36dhy";
char arr2[] = " -458";
char arr3[] = "myy123";
char arr4[] = "";
printf("%d\n", my_atoi(arr1));
printf("%d\n", my_atoi(arr2));
printf("%d\n", my_atoi(arr3));
printf("%d\n", my_atoi(arr4));
return 0;
}
从上面的例子我们大概分几个方面来解决这个问题
1.字符串为空
2.字符串中有’\0’
3.判断符号位
4.将字符转化为整数(考虑越界问题)
5.判断合法
直接断言就好了
#include
int my_atoi(char*p)
{
assert(p);
}
while (*p ==' ')
{
p++;
}
int flag = 1;//设定初始为+
if (*p == '+')
{
flag = 1;
p++;
}
else if (*p =='-')
{
flag = -1;
p++;
}
long long n=0;
while (*p != '\0')
{
if (isdigit(*p))
{
n = n* 10 + (*p - '0');
if (n > INT_MAX)//判断越界
{
return INT_MAX;
break;
}
if (n < INT_MIN)
{
return INT_MIN;
break;
}
}
else
{
break;
}
p++;
}
enum Status
{
VALID,
INVALID
}status = INVALID;
if (*p=='\0')
{
status = VALID;//这里我们用到了枚举
}
n = flag * n;
return (int)n;//强制转化为整形
#include
#include
#include
#include
enum Status
{
VALID,
INVALID
}status = INVALID;
int my_atoi(char*p)
{
assert(p);
if (*p == '\0')
{
return 0 ;
}
while (*p ==' ')
{
p++;
}
int flag = 1;
if (*p == '+')
{
flag = 1;
p++;
}
else if (*p =='-')
{
flag = -1;
p++;
}
long long n=0;
while (*p != '\0')
{
if (isdigit(*p))
{
n = n* 10 + (*p - '0');
if (n > INT_MAX)
{
return INT_MAX;
break;
}
if (n < INT_MIN)
{
return INT_MIN;
break;
}
}
else
{
break;
}
p++;
}
if (*p=='\0')
{
status = VALID;
}
n = flag * n;
return (int)n;
}
int main()
{
char arr1[] = "-36dhy";
char arr2[] = " -458";
char arr3[] = "myy123";
char arr4[] = "";
printf("%d\n", my_atoi(arr1));
printf("%d\n", my_atoi(arr2));
printf("%d\n", my_atoi(arr3));
printf("%d\n", my_atoi(arr4));
int n = my_atoi(arr2);
if (status == VALID)
{
printf("合法转化:n=%d\n", n);
}
else
{
printf("非法转换:n=%d\n", n);
}
return 0;
}