atoi函数介绍及模拟实现

1.函数介绍

在这里插入图片描述
atoi,将字符串转换成一个整形,函数返回转换后的整形。
在这里插入图片描述

int main()
{
	char str1[] = "1234"; // -> 1234
	char str2[] = "-1234";//添加负号-> -1234
	char str3[] = " 1234";//添加空格-> 1234
	char str4[] = "s1234";//头部添加字母 -> 0
	char str5[] = "12s34";//中部添加字母 -> 12
	char str6[] = " 12 34";//添加空格 -> 12
	
	printf("%d\n", atoi(str1));
	printf("%d\n", atoi(str2));
	printf("%d\n", atoi(str3));
	printf("%d\n", atoi(str4));
	printf("%d\n", atoi(str5));
	printf("%d\n", atoi(str6));

	return 0;
}

总结,函数会忽略前导空格
如果字符串第一个是数字或者+号,默认该数是正数,如果第一个字符-号,则转换后的数字是负数。

如果首字符是数字,函数不会返回0。如果不是数字字符或者空格,而是其他字符的话则返回0。

中间出现除了数字字符之外的其他字符函数会终止,包括空格。

2.atoi模拟实现

#include <math.h>
#include <ctype.h>

int my_atoi(const char* str)
{
	int flat = 1;
	int i = 0;
	while (*(str + i) == ' ')//忽略前导空格
		i++;

	if (*(str + i) == '-')//如果出现-号则把flat标记成-1
	{
		flat = -1;
		i++;
	}

	int tmp = 0;
	int count = 10;
	int k = 0;
	while (*(str + i) != '\0')
	{
		if (isdigit(*(str + i)))//用tmp倒着存储数字
		{
			tmp += (*(str + i) - '0') * pow(count, k++);
			i++;
		}
		else
			break;
	}

	int ret = 0;
	while (tmp)
	{
		ret += (tmp % 10) * pow(count, --k);//将倒着的数再次颠倒
		tmp /= 10;
	}

	return ret*flat;//flat数字的正负
}

int main()
{
	char str1[] = "1234";
	char str2[] = "-1234";//添加负号
	char str3[] = " 1234";//添加空格
	char str4[] = "s1234";//头部添加字母
	char str5[] = "12s34";//中部添加字母
	char str6[] = " 12 34";//添加空格
	char str7[] = " -s";//添加空格


	printf("%d\n", my_atoi(str1));
	printf("%d\n", my_atoi(str2));
	printf("%d\n", my_atoi(str3));
	printf("%d\n", my_atoi(str4));
	printf("%d\n", my_atoi(str5));
	printf("%d\n", my_atoi(str6));
	printf("%d\n", my_atoi(str7));
	return 0;
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值