Talking about the realization of atoi()

atoi ()

  1. Function: string to number

  2. Function implementation

     #include <stdio.h>
     #include <stdbool.h>
    
     int atoi(const char* str)
     {
     	int s = 0;
     	bool flag = false;
    
     	while (*str == ' ')
     	{
     		str++;
     	}
    
     	if (*str == '+' || *str == '-')
     	{
     		if (*str == '-')
     		{
     			flag = true;
     		}
     		str++;
     	}
     	else if (*str < '0' || *str > '9')
     	{
     		s = 216483548;
     		return s;
     	}
    
     	while (*str != '\0' && *str >= '0' && *str <= '9')
     	{
     		s = s * 10 + (*str - '0');
     		str++;
     	}
     	if (flag)
     	{
     		s = s * -1;
     	}
    
     	return s;
     }
    
     int main()
     {
     	char a[] = { "12345" };
     	int b = atoi(a);
     	printf("%s\n", a);
     	printf("%d\n", b);
     	return 0;
     }
    

Code analysis:
  Because the function of the function is to convert a string to a number, the return value is of type int, and the passed parameter is a string that does not need to be modified. There may be spaces in front of the string, so first advance the string subscript to The first string except the space, the number has positive and negative numbers, so set a benchmark flag, if there is a negative sign, it will be multiplied by -1 when the function returns, the string is converted to a number, and the ascll value is used for the difference Calculated, did not calculate that it is multiplied by 10 into one place.

Guess you like

Origin blog.csdn.net/weixin_43580319/article/details/113061569