1. Converting a string to an integer problem (C + +)
Follow the atoi implementation code:
//follow the Atoi function to convert the string into shaping data asked Title//#include "stdafx.h" enum Myenum{evalid = 0,//legal unvalid//illegal};int mstate = evalid;//Define a global variable, set the global variable when the input is not valid; It is possible to determine whether the input is valid by checking the global variable,//implementing string conversion to shaping data atoi problem int strtoint (char* str) {//variable initialization int number = 0;mstate = unvalid;//Judging string is No null if (str! = nullptr) {/******** Determines whether the character is legitimate *********///first determine whether the first bit is "+" or "-" bool minus = false;//positive and negative sign if (*str = = ' + ') {++str;} else if (*str = = '-') {++str;minus = true;} If both are not, then the ++str;/********* processing character conversion is not performed **********///determine if it is a valid character while ((*str >= ' 0 ') && (*str <= ' 9 ')) {number = Number * + (*STR-' 0 '); ++str;} Determine if the normal loop is complete if (*str = = ' + ') {//processing data Mstate = Evalid;if (minus) {number = 0-number;//converted to negative}}else//String error condition {number = 0;}} return number;} int _tmain (int argc, _tchar* argv[]) {//Test printf ("%d\n", Strtoint ("+23"));p rintf ("%d\n", Strtoint (" -23"));p rintf ("%d\ N ", Strtoint (" ")");p rintf ("%d\n", Strtoint ("A23")); return 0;}
Converting a string to an integer problem (c + +)