I assume you have this one function which can convert a single character to a number. Say it is int convert_one_char(const char c).
Given this function here is the code to extend it to convert a string with multiple chars:
int convert_one_char(const char c)
{
if( c == '0' ) return 0;
else if( c == '1' ) return 1;
else if( c == '2' ) return 2;
else if( c == '3' ) return 3;
else if( c == '4' ) return 4;
else if( c == '5' ) return 5;
else if( c == '6' ) return 6;
else if( c == '7' ) return 7;
else if( c == '8' ) return 8;
else if( c == '9' ) return 9;
else return -1 ;
}
long my_atoi( const string& s )
{
int curr_dec_multiplier = 10 ;
long ret_number = convert_one_char(s[s.length() - 1]) ;
for( int i = s.length() - 2; i >= 0; i-- )
{
ret_number += convert_one_char(s[i]) * curr_dec_multiplier ;
curr_dec_multiplier *= 10 ;
}
return ret_number ;
}
//------------------------------------------------
int main ()
{
cout << "523623412 converted = " << my_atoi("523623412") << endl ;
cout << "623412 converted = " << my_atoi("623412") << endl ;
cout << "231 converted = " << my_atoi("231") << endl ;
//-----------------------
getch() ;
return 0;
}
//------------------------------------------------
You'll need to put in appropriate error handling code...
thekashyap
Practically a Posting Shark
811 posts since Feb 2007
Reputation Points: 254
Solved Threads: 75