Convert string to integer "123"-) 123
String to integer "123"-> 123
Description:
Enter a string composed of digits, convert it to an integer, and output it. For example, input string "123" and output integer 123.
Given function prototypeint StrToInt(const char *str)
To convert a string to an integer. You cannot use the database function atoi.
Question Analysis:
To convert a string to an integer
① When scanning the first character '1', the number 1 is obtained directly because it is the first character.
② When scanning the second character '2,1*10+2 = 12
③ When the scan character '3' continues,12*10+3=123
That's whyn = n * 10 + c;
Easy to error:
1) it cannot be a null pointer. Otherwise, the program will crash when the NULL pointer is accessed.if(str == NULL)return 0;
2) Positive and Negative symbols must be considered.Add sign
3) consider invalid characters, such as spaces.While (isspace (* str) ++ str also needs to be detected when it is a number before conversion starts.
4) integer overflow. If a long and long string is input, it may be converted into integer overflow.Method 1: The n type can be defined as long. Method 2: Use the MAX_INT and MIN_INT types to compare the sizes of n and MAX_INT/10.
<<
Reference code:
Int StrToInt (const char * str) {// reverse the value of 0 and move one static const int MAX_INT = (int) (unsigned )~ 0> 1); static const int MIN_INT =-(int) (unsigned )~ 0> 1)-1; unsigned int n = 0; // determines whether it is NULL if (str = NULL) return 0; // process space while (isspace (* str) + + str; // process positive and negative int sign = 1; if (* str = '+' | * str = '-') {if (* str = '-') sign =-1; ++ str ;} // after confirming the number, start converting while (isdigit (* str) {// handle overflow int c = * str-'0 '; if (sign> 0 & (n> MAX_INT/10 | (n = MAX_INT/10 & c> MAX_INT % 10) {n = MAX_INT; break ;} else if (sign <0 & (n> (unsigned) MIN_INT/10 | (n = (Unsigned) MIN_INT/10 & c> (unsigned) MIN_INT % 10) {N = MIN_INT; break;} n = n * 10 + c; ++ str;} return sign> 0? N:-n ;}