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)