介绍:C语言—atoi函数

atoi函数:

在C语言中,atoi 函数用于将字符串转换为整数。这个函数的原型如下:

int atoi(const char *str);

  • str 是指向要转换的字符串的指针。首先根据需要丢弃尽可能多的空格,直到找到第一个非空格字符。从此字符开始,字符字符串应该以数字字符开始,可以有一个可选的符号(+ 或 -),后面跟着数字字符。atoi 函数会读取 str,直到遇到一个非数字字符或字符串结束符 \0
  • 如果 str 是有效的整数字符串,atoi 函数会返回相应的整数值。如果 str 不是有效的整数字符串,atoi 函数的行为是未定义的。

下面是一个使用 atoi 函数的简单示例:

#include <stdio.h>
#include <stdlib.h>

int main() {
    char str1[] = "42";
    char str2[] = "-123";
    char str3[] = "10abc";

    int num1 = atoi(str1);
    int num2 = atoi(str2);
    int num3 = atoi(str3);

    printf("num1: %d\n", num1); // 输出:num1: 42
    printf("num2: %d\n", num2); // 输出:num2: -123
    printf("num3: %d\n", num3); // 输出:num3: 10

    return 0;
}

在这个示例中,atoi 函数成功地将字符串 "42""-123" 和 "10abc" 转换为了整数42、-123和10.

需要注意的是,由于 atoi 函数在转换失败时的行为是未定义的,因此在实际使用中,通常推荐使用 strtol 或 sscanf 等函数,因为这些函数提供了更好的错误处理机制。

模拟实现atoi:

#include<stdio.h>
#include<assert.h>
#include<ctype.h>
#include <limits.h>


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 ret = 0;
	while (*str != '\0')
	{
		if (isdigit(*str))
		{
			ret = ret * 10 + flag * (*str - '0');//减去字符0,才是数字0
			if (ret > INT_MAX || ret < INT_MIN)
				return 0;
		}
		str++;
	}
	return (int)ret;//强制类型转化为int(函数的返回值是int)
	
}
int main()
{
	char s[100] = "    43";
	printf("%d\n", my_atoi(s));
	return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_73800602/article/details/133273856