1)
In your function str
as an automatic variable on the stack was destroyed after the int_to_string
returned. But you need str
to be alive for more int_to_string
calls! So you have to preserve str
between calls.
2)
case 0: return "Zero";
....
The code above will not work properly in recursion calls, the word "Zero" has to be added to str
string
case 0: strcat(str,"Zero"); return str;
But why suffer with recursion calls? Recursion can be replaced with a simple loop. Both solutions are shown.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
void print_digit(int digit)
{
switch(digit)
{
case '0': printf("Zero "); break;
case '1': printf("One "); break;
case '2': printf("Two "); break;
case '3': printf("Three ");break;
case '4': printf("Four "); break;
case '5': printf("Five "); break;
case '6': printf("Six "); break;
case '7': printf("Seven ");break;
case '8': printf("Eight ");break;
case '9': printf("Nine "); break;
}
}
char * return_digit_word(int digit)
{
switch(digit)
{
case '0': return("Zero "); break;
case '1': return("One "); break;
case '2': return("Two "); break;
case '3': return("Three ");break;
case '4': return("Four "); break;
case '5': return("Five "); break;
case '6': return("Six "); break;
case '7': return("Seven ");break;
case '8': return("Eight ");break;
case '9': return("Nine "); break;
}
}
char *int_to_string(int n,char str[],char numStr[])
{
if(n<10)
{
switch(n)
{
case 0: strcat(str,"Zero");break;
case 1: strcat(str,"One");break;
case 2: strcat(str,"Two");break;
case 3: strcat(str,"Three");break;
case 4: strcat(str,"Four");break;
case 5: strcat(str,"Five");break;
case 6: strcat(str,"Six");break;
case 7: strcat(str,"Seven");break;
case 8: strcat(str,"Eight");break;
case 9: strcat(str,"Nine");break;
}
return str;
}
else{
int digit = numStr[0]-'0';
int newNr = n - digit*pow(10,strlen(numStr)-1);
strcat(str, return_digit_word(numStr[0]));
sprintf(numStr, "%d", newNr);
return int_to_string(newNr,str,numStr);
}
}
int main(void) {
int n,i;
char str[100]="";
char numStr[100]="";
n = 1234567890;
sprintf(numStr, "%d", n);
printf("\n%d in words is : %s\n",n, int_to_string(n,str,numStr) );
printf("\n%d in words is : ",n);
sprintf(numStr, "%d", n);
for(i=0;i<strlen(numStr);i++)
{
print_digit(numStr[i]);
}
return 0;
}
Output for n=1234567890:
1234567890 in words is : One Two Three Four Five Six Seven Eight Nine Zero
1234567890 in words is : One Two Three Four Five Six Seven Eight Nine Zero