atoi的函数声明及功能如下:
这个函数的功能是将字符串转换为整形,那么具体是怎么样的呢
先看几个例子:
当字符串中的数字前有空白字符时,会把空白字符去掉。
当字符串中间有字母时,只会转换字母前的数字。
字符串数字超过最大整形表示的范围时,返回整形最大值(最小值同理)。
空格后第一个字符是字母,会返回0。
因此,我们模拟实现时,要考虑以上几种非法输入情况:
1.空字符串
2.空白字符
3.处理+-号
4.过大值过小值
5.数字中间有其他字符
atoi模拟实现:
#include <stdio.h>
#include <ctype.h>
#include <assert.h>
#include <stdlib.h>
enum State
{
VALID,
INVALID
}sta = INVALID;//默认设置为非法
int my_atoi(const char* str)
{
//空指针
assert(str);
//空字符串
if (*str == '\0')
return 0;
//跳过空白字符
while (isspace(*str))
{
str++;
}
//处理+-
int flag = 1;
if (*str == '+')
{
flag = 1;
str++;
}
else if(*str == '-')
{
flag = -1;
str++;
}
long long r = 0;
while (*str)
{
if(isdigit(*str))
{
r = r * 10 + flag*((long long)*str - '0');
if (r > INT_MAX || r < INT_MIN)
{
if (flag == 1)
return INT_MAX;
else
return INT_MIN;
}
str++;
}
else
{
return (int)r;
}
}
sta = VALID;
return (int)r;
}
int main()
{
char arr[] = " 12ab34";//加几个空格
int ret = my_atoi(arr);
if (sta == VALID)
printf("合法的转换:%d\n", ret);
else
printf("非法的转换:%d\n", ret);
return 0;
}
在模拟实现过程中,我们定义了枚举类型State,目的是为了避免歧义,比如,当给my_atoi传入空字符串时,函数返回0,同时,当给my_atoi传入字符串"0"时,函数也应该返回0,这势必会造成歧义,因此,才定义了这样一个枚举类型,用枚举类型定义一个枚举变量sta,初始值为INVALID,当函数正常返回时,sta置为VALID,最终根据sta的值区分歧义!