content
1.1 Implementation of atoi function
2. Simulation implementation of atoi function
1.atoi function
Header file #include<stdlib.h>
Declaration of atoi function int atoi(const char *str)
The atoi function converts the string pointed to by the parameter str into an integer (int type).
1.1 Implementation of atoi function
#include <stdlib.h>
int main()
{
int a = 0;
char str[20] = "1234";
a=atoi(str);
printf("%d\n", a);
return 0;
}
2. Simulation implementation of atoi function
#include<assert.h>
#include<ctype.h>
#include <stdlib.h>
enum Status
{
VALID,
INVALID
}status=INVALID;//非法
int my_atoi(const char* str)
{
int flag = 1;
//空指针
assert(str);
//字符串为空
if (*str == '\0')
{
return 0;//
}
//空白字符
while (isspace(*str))
{
str++;
}
//正负号
if (*str == '+')
{
flag = 1;
str++;
}
if (*str == '-')
{
flag = -1;
str++;
}
long long n = 0;
while (*str != '\0')
{
if (isdigit(*str))
{
n = n * 10 + flag * (*str - '0');
if (n<INT_MIN || n>INT_MAX)
{
n = 0;
break;
}
}
else
{
break;
}
str++;
}
if (*str == '\0')
{
status = VALID;
}
return (int)n;
}
int main()
{
char arr[20] = " -1234";
int ret = my_atoi(arr);
if (status == VALID)
printf("正常转化 %d\n", ret);
else
printf("非法转化 %d\n", ret);
printf("%d\n", ret);
return 0;
}
The simulation results are as follows