hi , im pretty new to computer science and alose to this community . i have a problem that im trying to solve and hope you guys can help me with it . im trying to create my own version of the function "atoi" that can be found in stdlib and i cant get it to work . i know how to convert a single char from the string to and int , but its starting to be a problem when im trying to convert a number like "111" , if any1 can help it could be great . thanks ...
RisTar
- 3 Contributors
- forum3 Replies
- 5 Views
- 11 Years Discussion Span
- comment Latest Post by RisTar
thekashyap 193
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...
Ancient Dragon 5,243
To convert a single character to an int just simply subtract '0' from its ascii value
char c = '1';
int num = c - '0';
When converting several characters to int you have to multiply the previous value by 10 to make room for the new digit.
Below num is an integer and digits is a character array that contains all the digits. This code snipped would be placed inside a loop.
num = (num * 10) + digits[i] - '0';
RisTar
Thanks guys , you were totally helpful .