Programming algorithms-Converting a string to an integer code (C)

Source: Internet
Author: User

converts a string to an integer code (C)


This address: Http://blog.csdn.net/caroline_wendy


Title: Write a function strtoint, simulate the function of Atoi, convert the string to an integer.


You need to consider exception handling, positive negative numbers, and the maximum value of int (0x7FFFFFFF) and minimum (0x80000000) .


Code:

/* * main.cpp * * Created on:2014.7.12 * author:spike * * #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h>enum Status {kvalid=0, kinvalid};int g_nstatus = Kvalid;long long Strtointcore ( Const char* Digit, bool minus) {long Long num = 0;while (*digit! = ') ') {if (*digit >= ' 0 ' && *digit <= ' 9 ' ) {int flag = minus?

-1:1;num = num*10 + flag* (*digit-' 0 '); if (!minus && num>0x7fffffff) | | (Minus && num < (signed int) 0x80000000)) {num = 0;break;} digit++;} else {num = 0;break;}} if (*digit = = ' + ') {g_nstatus = Kvalid;} return num;} int strtoint (const char* str) {g_nstatus = Kinvalid;long long num = 0;if (str! = NULL && *str! = ') ' {bool minus = False;if (*str = = ' + ') str++;else if (*str = = '-') {Str++;minus = true;} if (*str! = ') num = Strtointcore (str, minus);} return (int) num;} int main (void) {char num[] = " -873141"; int result = Strtoint (num); printf ("result =%d\n", result); return 0;}


Output:

result =-873141








Programming algorithms-Converting a string to an integer code (C)

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.