D
dgoodmaniii
+AMDG
I'm having lots of trouble with K&R's Exercise 4-12, which
asks for a recursive version of itoa(n, s), which puts a
string version of integer n into string s. I had no trouble
doing this without recursion and the reversing it, but with
recursion I just can't figure it out.
Here's what I've got:
*******************
int itoa(int n, char s[])
{
static int i = 0;
if (n / 10) {
itoa(n / 10,s);
} else {
s[--i] = '\0';
i = 0;
}
if (n < 0 && i == 0) {
s[i++] = '-';
n = -n;
}
s[i++] = (n % 10 + '0');
return 0;
}
*******************
I'm testing it with the following for loops:
*******************
for (i=-11; i<=11; ++i) {
itoa(i,s);
printf("%s ",s);
}
putchar('\n');
for (i=11; i>=-11; --i) {
itoa(i,s);
printf("%s ",s);
}
putchar('\n');
*******************
It seems to work perfectly fine for positive numbers, and
for negative numbers of a single digit. After that, it
fails ingloriously, appropriately producing the negative
symbol and the first digit but spewing several digits of
garbage thereafter.
Can anyone help me out with this?
I'm having lots of trouble with K&R's Exercise 4-12, which
asks for a recursive version of itoa(n, s), which puts a
string version of integer n into string s. I had no trouble
doing this without recursion and the reversing it, but with
recursion I just can't figure it out.
Here's what I've got:
*******************
int itoa(int n, char s[])
{
static int i = 0;
if (n / 10) {
itoa(n / 10,s);
} else {
s[--i] = '\0';
i = 0;
}
if (n < 0 && i == 0) {
s[i++] = '-';
n = -n;
}
s[i++] = (n % 10 + '0');
return 0;
}
*******************
I'm testing it with the following for loops:
*******************
for (i=-11; i<=11; ++i) {
itoa(i,s);
printf("%s ",s);
}
putchar('\n');
for (i=11; i>=-11; --i) {
itoa(i,s);
printf("%s ",s);
}
putchar('\n');
*******************
It seems to work perfectly fine for positive numbers, and
for negative numbers of a single digit. After that, it
fails ingloriously, appropriately producing the negative
symbol and the first digit but spewing several digits of
garbage thereafter.
Can anyone help me out with this?