[C ++ primer] Write the function atoi (char * Str) by yourself)

Source: Internet
Author: User

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;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.