Using Basic C++ #define ENOUGH_SIZE 10 char* itoa_plain(int value) { char* digits = new char[ENOUGH_SIZE]; char* temp = new char[ENOUGH_SIZE]; digits[0] = '\0'; do { int lastDigit = value % 10; value = value / 10; temp[0] = lastDigit + '0'; temp[1] = '\0'; strncat(temp, digits, strlen(digits)); strcpy(digits, temp); }while(value != 0); return digits; }
Using standard library char* itoa_standard(int value) { std::string digits; do { int lastDigit = value % 10; value = value / 10; digits.insert(digits.begin(), lastDigit + '0'); }while(value != 0); const unsigned long resultSize = digits.length(); char* result = new char[resultSize]; digits.copy(result, resultSize); result[resultSize] = 0; return result; }
An alternate solution:
ReplyDeletechar* my_itoa( int value, char* buf )
{
char* p = buf;
while ( value > 0 )
{
*(p++) = ( (value % 10) + '0' );
value /= 10;
}
*p = '\0';
strrev( buf );
return buf;
}