Sword Point of Offer question 49th: Converting a string to an integer
1 //============================================================================2 //Name:jz-c-49.cpp3 //Author:laughing_lz4 //Version:5 //Copyright:all Right Reserved6 //Description: Converting a string to an integer7 //============================================================================8 9#include <iostream>Ten#include <stdio.h> One#include <stdlib.h> A using namespacestd; - - Long LongStrtointcore (Const Char* STR,BOOLminus); the - enumStatus { -Kvalid =0, Kinvalid//at this point kinvalid is 1, and if there is no requirement to define the enum variable, the value of the enumeration variable can be omitted. In the above form, the first value defaults to 0, and the following each is the previous value plus 1. - }; + intG_nstatus = Kvalid;//define global variables to reflect whether the input is legitimate - + intStrtoint (Const Char*str) { AG_nstatus = Kinvalid;//Initial 1: illegal at Long Longnum =0;//A long long storage conversion of STR, the actual return is the INT type ★ - - if(str! = NULL && *str! =' /') {//consider a null pointer null or string NULL "", the function returns 0 directly, and the global variable g_nstatus is 1, illegal - BOOLminus =false;//consider positive or negative - if(*str = ='+') -str++; in Else if(*str = ='-') { -str++; tominus =true; + } - the if(*str! =' /') { *num =Strtointcore (str, minus); $ }Panax Notoginseng } - the return(int) Num;//Convert long long num to int + } A the Long LongStrtointcore (Const Char* Digit,BOOLminus) { + Long Longnum =0; - $ while(*digit! =' /') { $ if(*digit >='0'&& *digit <='9') { - intFlag = minus? -1:1; -num = num *Ten+ Flag * (*digit-'0'); the //consider overflow - if((!minus && num >0x7FFFFFFF)//the largest positive integer that int can representWuyi|| (Minus && Num < (signedint)0x80000000)) {//the smallest negative integer that int can represent thenum =0; - Break; Wu } - Aboutdigit++; $}Else { -num =0; - Break; - } A } + the if(*digit = =' /') { -G_nstatus =Kvalid; $ } the the returnnum; the } the - //==================== test Code ==================== in voidTest (Char*string) { the intresult = Strtoint (string); the if(Result = =0&& G_nstatus = =kinvalid) Aboutprintf"The input%s is invalid.\n",string); the Else theprintf"Number for %s is:%d.\n",string, result); the } + - intMainintargcChar**argv) { the Test (NULL);Bayi theTest (""); the -Test ("123"); - theTest ("+123"); the theTest ("-123"); the -Test ("1a33"); the theTest ("+0"); the 94Test ("-0"); the the //valid maximum positive integer, 0x7FFFFFFF theTest ("+2147483647");98 AboutTest ("-2147483647"); - 101Test ("+2147483648");102 103 //valid minimum negative integer, 0x80000000104Test ("-2147483648"); the 106Test ("+2147483649");107 108Test ("-2147483649");109 theTest ("+");111 theTest ("-");113 the return 0; the}
jz-c-49