详解 atoi 函数并模拟实现

目录

一、函数说明

二、返回值

三、模拟实现



函数原型:

int atoi(const char* str);

所属头文件:stdlib.h

一、函数说明

将字符串转换为整数(Convert string to integer)

  • The function first discards as many whitespace characters (as in isspace) as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many base-10 digits as possible, and interprets them as a numerical value.

    isspace

    int isspace(int c);

    所属头文件ctype.h

    函数说明:检查 c 是否为空白字符(Checks whether c is a white-space character)。空白字符可以是下面中的任意字符:

    空白字符十进制意义
    ' '32空格(space)
    '\t'9水平制表符(horizontal tab)
    '\n'10换行(newline)
    '\v'11垂直制表符(vertical tab)
    '\f'12换页(form feed)
    '\r'13回车(carriage return)

    返回值:如果 c 确实是一个空白字符,则返回一个非零值,即 true;否则,返回零,即 false。

  • The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

    字符串可以在构成整数的字符之后包含其他字符,这些字符将被忽略,并且对此函数的行为没有影响

  • If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed and zero is returned.

    如果 str 中的第一个非空白字符序列不是有效的整数,或者由于 str 为空或仅包含空白字符而不存在此类序列,则不执行转换并返回零

二、返回值

On success, the function returns the converted integral number as an int value.

成功后,该函数将转换后的整数作为 int 值返回

If the converted value would be out of the range of representable values by an int, it causes undefined behavior.

如果转换后的值超出 int 的可表示值范围,则会导致未定义的行为

三、模拟实现

int my_atoi(const char* str)
{
	assert(str);
	typedef enum Sign
	{
		NEGTIVE = -1,
		POSITIVE = 1
	}Sign;
	// 首先跳过空白字符
	while (isspace(*str))
	{
		str++;
	}
	// 然后根据第一个非空白字符确定正负号
	Sign flag = POSITIVE;  // 默认为正号
	if (*str == '+')
	{
		str++;
	}
	else if (*str == '-')
	{
		flag = NEGTIVE;
		str++;
	}
	// 确定返回值并返回
	int ret = 0;
	while (*str >= '0' && *str <= '9')
	{
		ret = ret * 10 + flag * (*str - '0');
		str++;
	}
	return ret;
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值