atoi function and its simulation implementation

 The function declaration and functions of atoi are as follows:

The function of this function isconvert a string into an integer, so what exactly does it do

Let’s look at a few examples first:

 When there are blank characters before numbers in the string, the blank characters will be removed.

 When there are letters in the middle of the string, only the numbers before the letters will be converted.

 When the string number exceeds the range of the maximum integer representation, the maximum integer value is returned (the same applies to the minimum value).

There is a maximum value converted to an integer

 If the first character after the space is a letter, 0 will be returned.

It was an illegal character at the beginning

Therefore, when we simulate implementation, we must consider the above illegal input situations:

1. Empty string

2. Blank characters

3. Process +- sign

4. Too large value and too small value

5. There are other characters in the middle of the numbers

atoi simulation implementation:

#include <stdio.h>
#include <ctype.h>
#include <assert.h>
#include <stdlib.h>
enum State
{
	VALID,
	INVALID
}sta = INVALID;//默认设置为非法
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 r = 0;
	while (*str)
	{
		if(isdigit(*str))
		{
			r = r * 10 + flag*((long long)*str - '0');
			if (r > INT_MAX || r < INT_MIN)
			{
				if (flag == 1)
					return INT_MAX;
				else
					return INT_MIN;
			}
			str++;
		}
		else
		{
			return (int)r;
		}
	}
	sta = VALID;
	return (int)r;

}

int main()
{
	char arr[] = "   12ab34";//加几个空格
	int ret = my_atoi(arr);
	if (sta == VALID)
		printf("合法的转换:%d\n", ret);
	else
		printf("非法的转换:%d\n", ret);

	return 0;
}

During the simulation implementation process, we defined the enumeration type State to avoid ambiguity. For example, when an empty string is passed to my_atoi, the function returns 0. At the same time, when the string "0" is passed to my_atoi , the function should also return 0, which will inevitably cause ambiguity. Therefore, such an enumeration type is defined. An enumeration variable sta is defined using the enumeration type. The initial value is INVALID. When the function returns normally, sta is set to VALID. , and ultimately the meaning is differentiated based on the value of sta!

Guess you like

Origin blog.csdn.net/qq_48460693/article/details/133803494