I. Requirement: Write the atoi (char * Str) function by yourself. The function is to convert a string into a number.
Simple version:
Where to consider: 1) Positive and Negative
2) Only decimal
3) how to convert numeric characters into Integers
4) whether each character is a number
# Include <iostream> using namespace STD; int strtoint (char * Str) {int value = 0; int Sign = 1; if (* STR = '-') // negative sign {Sign =-1; STR ++;} while (* STR> = '0' & * STR <= '9') // This method is clever, directly start from the high position and multiply the value. You do not need to consider the string length {value = value * 10 + * str-'0'; STR ++;} return sign * value ;} int main () {cout <strtoint ("123") <Endl; return 0 ;}
Of course, you can also use strlen or the end character to find the second digit. The multiplier can be changed. 2. Enhanced Edition The followingProgramTake into account octal, decimal, and hexadecimal strings.
Int strtoint (char * Str) {int value = 0; int Sign = 1; int Radix; If (* STR = '-') {Sign =-1; STR ++;} If (* STR = '0' & (* (STR + 1) = 'X' | * (STR + 1) = 'X') {Radix = 16; STR + = 2;} else if (* STR = '0 ') // The first character of gossip is 0 {Radix = 8; STR ++;} else Radix = 10; while (* Str) {If (Radix = 16) {If (* STR> = '0' & * STR <= '9') value = value * Radix + * str-'0 '; else value = value * Radix + (* STR | 0x20)-'A' + 10; // value = value * Radix + * str-'A' + 10; // No problem.} else value = value * Radix + * str-'0'; STR ++;} return sign * value ;} integer Conversion to string void ITOA (int n, char s []) {int I, j, sign; If (Sign = N) <0) // record symbol N =-N; // make n a positive number I = 0; do {s [I ++] = N + '0 '; // take the next digit} while (n/= 10)> 0); // Delete the digit if (sign <0) s [I ++] = '-'; s [I] = '\ 0'; For (j = I; j> = 0; j --) // The generated numbers are in reverse order, therefore, printf ("% C", s [J]) needs to be output in reverse order;}