Introduction: C language—atoi function

atoi function:

In C language, atoi functions are used to convert strings to integers. The prototype of this function is as follows:

int atoi(const char *str);

  • str is a pointer to the string to be converted. First discard as many spaces as necessary until the first non-space character is found. Starting from this character, the character string should start with a numeric character and may have an optional symbol ( + or  -) followed by a numeric character. atoi The function reads  struntil it encounters a non-numeric character or the end of the string  \0.
  • If  str it is a valid integer string, atoi the function returns the corresponding integer value. If it  str is not a valid integer string, atoi the behavior of the function is undefined.

Here's a  atoi simple example using a function:

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

In this example, atoi the function successfully converts the strings  "42", "-123" and  "10abc" into the integers 42, -123, and 10.

It should be noted that since  atoi the behavior of the function when the conversion fails is undefined, in actual use, it is usually recommended to use  functions such strtol as  sscanf or because these functions provide better error handling mechanisms.

Simulate the implementation of 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;
}

Guess you like

Origin blog.csdn.net/m0_73800602/article/details/133273856