Programming Algorithm-convert a string to an integer code (c)

Source: Internet
Author: User
Convert string to integer code (c)


Address: http://blog.csdn.net/caroline_wendy


Question: Write A strtoint function to simulate the atoi function and convert the string to an integer.


ConsiderationsException Handling, positive and negative,And intMaximum (0x7fffffff) and minimum (0x80000000)And so on.


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 != ‘\0‘) {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 == ‘\0‘) {g_nStatus = kValid;}return num;}int StrToInt(const char* str) {g_nStatus = kInvalid;long long num = 0;if (str != NULL && *str != ‘\0‘) {bool minus = false;if (*str == ‘+‘)str++;else if (*str == ‘-‘) {str++;minus = true;}if (*str != ‘\0‘)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








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.