[C Language] implements a function int my_atoi (char s []) to convert a string to a corresponding integer.

Source: Internet
Author: User

[C Language] implements a function int my_atoi (char s []) to convert a string to a corresponding integer.

# Include <stdio. h> int my_atoi (char s [5]) {int flag = 1; // in this case, int ret = 0; char * p = s; if (* p = '-') // if the first character is '-', the flag switch is enabled and set to-1; {flag =-1 ;} if (* p = '+' | * p = '-') // if the first character is '-' or '+', no processing is performed, jump directly to the second character {p ++;} while (* p! = '\ 0') {if (* p> = '0') & (* p <= '9') // because it must be an integer, so only 0 ~ Number between 9 {ret = ret * 10 + * p-'0'; // obtain each digit, and then accumulate p ++ according to the law in decimal ;}} return flag * ret;} int main () {int ret = 0; char s [5]; gets (s); ret = my_atoi (s ); // receives the return value of the atoi function printf ("% d \ n", ret); return 0 ;}

 

Related Article

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.