模拟实现atoi——C语言

目录

1.atoi函数

1.1 atoi函数的实现

2. atoi函数的模拟实现


1.atoi函数

头文件 #include<stdlib.h>

atoi函数的声明                       int atoi(const char *str)

atoi函数是将参数str所指向的字符串转换为一个整数(int型)。

1.1 atoi函数的实现

#include <stdlib.h>
int main()
{
	int a = 0;
	char str[20] = "1234";
	a=atoi(str);
	printf("%d\n", a);
	return 0;
}

2. atoi函数的模拟实现

#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;
}

模拟实现结果如下

猜你喜欢

转载自blog.csdn.net/weixin_53939785/article/details/124061567