//author@ Jolex Del Pilar //Implementing ATOI in C++ #include using namespace std; int myAtoi(char * pStr); //Prototype int strLength(char * pStr); //Find the length of the passed string int main() { char * testInput; testInput = "-1a2v5h+4"; cout << "Value: " << myAtoi(testInput) << endl; cout << "String Length: " << strLength(testInput) << endl; } int myAtoi(char * pStr) { int ret_value = 0; //Store the value int i; //for loop counter int temp; //Holder for number //Check if NULL string passed if ( NULL == pStr ) { return 0; } //int len = strlen(pStr)-1; //Length of the string being passed (using STL) int len = strLength(pStr); //Length of the string being passed for(i = 0; i <= len; i++) { if ( (pStr[i] >= '0')&&(pStr[i] <= '9') ) //We only want digits 0-9, nothing else... { temp = ( pStr[i]-'0' ); //Converting an ASCII numeric character to its internal(integral). '9' - '0' == 9 ret_value = ret_value*10 + temp; //Enlarge the number by *10 every time } } return ret_value; } int strLength(char * pStr) { int inc; int lenCount = 0; for(inc = 0; pStr[inc] != NULL; inc++) { lenCount++; } return lenCount; }