The text for this exercise reads:
Write a function itoa(int i, char b[]) that creates a string representation of i in b and returns b.
I updated this at the 14th April 1999. I used to do two loops, one to make the number in reverse order, another to copy the string in reverse order. Nothing serious, just that making the first loop do the number in the correct order and then copy as it is will probably be slightly more efficient.
char* itoa(int i, char b[]) { char buf[32]; char* tp = buf + sizeof buf; *--tp = '\0'; bool neg = false; if (i < 0) { neg = true; i = -static_cast(i); } int j = 0; do { //a simple while loop would fail if (i == 0); if (j++ % 4 == 3) // a little pretty detail { *--tp = ' '; ++j; // necessary, if I was to do an if (j++ % 3) it would resolve to true at the first pass } *--tp = '0' + (i % 10); // You are guaranteed by the Standard that numbers i /= 10; // are in order in the character set, i.e. '0' + 5 == '5' }while (i); char* sp = b; // simply using b won't work since you must return it unmodified if (neg) *sp++ = '-'; strcpy(sp,tp); return b; }
If you consider using strcpy cheating, you can alway do while (*sp++ = *tp++);.
This was by old version:
char* itoa(int i, char b[]) { int j = 0; bool neg = false; if (i < 0) { neg = true; i *= -1; } const int size = 32; //suffices, unless you have really big ints char tmp[size]; do { //a simple while loop would fail if (i == 0); if (j%4 == 3) // a little pretty detail tmp[j++] = ' '; char c = '0'; // You are guaranteed by the Standard that numbers c += i%10; // are in order in the character set, i.e. '0' + 5 == '5' tmp[j++] = c; i /= 10; } while (i); if (neg) tmp[j++] = '-'; int k = 0; while (j) b[k++] = tmp[--j]; b[k] = '\0'; return b; }
Actually I had written this function long ago when I wanted to print big numbers in a readable way. It works and it was easy to write.