Key Point: various illegal parameters should be taken into account.
Implementation:
/********************************* String to integer by rowandjj2014 /7/15 ***********************************/# include <iostream> # include <stdlib. h> // if this header file is not added, the compilation Error Using namespace STD; int state = 0; // 0 indicates that the string is invalid, 1 stands for normal long str2int (const char * Str) {long num = 0; If (STR = NULL) // enter null {state = 0; return 0 ;} const char * digit = STR; int minius = 0; // 0 indicates a positive number, and 1 indicates a negative number while (* digit = '') // skip spaces {digit ++ ;} if (* digit = '+') {digit ++ ;} Else if (* digit = '-') {minius = 1; digit ++;} If (* digit = '\ 0 ') // only enter + or-{state = 0; return 0;} while (* digit! = '\ 0') {If (* digit> '9' | * digit <'0') // invalid character {state = 0; return 0 ;} state = 1; num = num * 10 + (* digit-'0'); // core code digit ++ ;} // If (* digit> 0x7fffffff | * digit <(signed INT) 0x80000000) {state = 0; return 0;} return minius? (0-num): num;} int main () {long digit; char STR [1000]; char * P = STR; while (CIN> P) {digit = str2int (p); If (State = 0) {cout <"My God \ n ";} else // state = 1 {cout <digit <Endl ;}} return 0 ;}