C language: please write a program to realize the conversion of string to integer, for example, output string "12345", output integer 12345

Title: please write a program to realize the conversion from string to integer, for example, output string "12345", output integer 12345

This problem seems very simple. Through analysis, we can easily write the following code:

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

 int my_atoi(const char* str)
{
	 int ret = 0;
	 assert(str!=NULL);
	 while (*str)
	 {
		 ret = ret * 10 + *str- '0';
		 str++;
	 }
	return ret;
}


int main()
{
	char *p = "12345";
	int ret = my_atoi(p);
	printf("%d\n", ret);
	system("pause");
	return 0;
}

But is that right? In fact, it's not. We just consider one of the simplest cases. If we give an empty string, for example, if we give "- 123" or "+ 123", if "+," - "are calculated by subtracting the character 0, the result will be unexpected, so we don't consider the problem of plus and minus signs. Also, if a given string is preceded by a space or table Well, so we didn't consider the situation of these white space characters; so, what if the given string is a fairly long string? The most we can receive is more than 4.2 billion, so we haven't considered the problem of cross-border. To sum up, the correct code is as follows:

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

enum State
{
	VALID, //Legal status
	INVALID //Illegal state
};
enum State state = INVALID;//Because there are many illegal States and only one legal state, in order to make the code simpler, the start state is initialized to illegal state
 int my_atoi(const char* str)
{
	long long ret = 0;
	 int flag = 1;//Identify positive and negative numbers
	 assert(str != NULL);//Null pointer
	 if (*str == '\0')//Empty string
	 {
		 return 0;
	 }
	while(isspace(*str))   //Blank character
	 {
		str++;
	 }
	if (*str == '+')
	{
		str++;
	}
	else if (*str == '-')
	{
		str++;
		flag = -1;
	}

	 while (*str)
	 {
		 if (isdigit(*str))
		 {
			 ret = ret * 10 + (*str - '0')*flag;
			 if (ret > INT_MAX&&ret < INT_MIN)//Cross-border situation
			 {
				 return 0;
			 }
		 }
		 else
		 {
			 state = VALID;//Legal status
			return (int)ret;
		 }
		 str++;
	 }
	 state = VALID;
	return (int)ret;
}


int main()
{
	char *p = "  123abc567";
	int ret = my_atoi(p);
	if (state==VALID)
	printf("%d\n", ret);
	system("pause");
	return 0;
}

 

Added by xentia on Mon, 06 Jan 2020 22:41:36 +0200