#include<stdio.h>
#include<string.h>
char *int_to_string( int n );
void main()
{
int n;
printf("Enter the number : ");
scanf("%d",&n);
printf("\n%d in words is : %s.\n",n,int_to_string(n));
}
char *int_to_string( int n)
{
char str[100]="";
if(n<10)
{
switch(n)
{
case 0: return "Zero";
case 1: return "One";
case 2: return "Two";
case 3: return "Three";
case 4: return "Four";
case 5: return "Five";
case 6: return "Six";
case 7: return "Seven";
case 8: return "Eight";
case 9: return "Nine";
}
}
else
{
strcat(str,int_to_string(n/10));
strcat(str," ");
return strcat(str,int_to_string(n%10));
}
}
Function int_to_string() should return a string containing equivalent of the number in words that is passed. it works fine for single digit number ( i.e. 0-9 ) but above that it just gives nothing.
The function has undefined behaviour.
It returns a pointer to local array str
that is in general destroyed after exiting the function.
Take into account that it is better to define the parameter as having type unsigned int
. Otherwise the function needs to check whether the number is not negative.
You could make the task easier by means of declaring second parameter that will specify a character zero-terminated array that will store the result string.
Or you have to allocate memory dynamically.
Here are shown these two approaches.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
char * int_to_string( unsigned int n )
{
if( n < 10 )
{
char *p = "";
switch( n )
{
case 0:
p = "Zero";
break;
case 1:
p = "One";
break;
case 2:
p = "Two";
break;
case 3:
p = "Three";
break;
case 4:
p = "Four";
break;
case 5:
p = "Five";
break;
case 6:
p = "Six";
break;
case 7:
p = "Seven";
break;
case 8:
p = "Eight";
break;
case 9:
p = "Nine";
break;
}
char *q = malloc( strlen( p ) + 1 );
strcpy( q, p );
free( p );
return q;
}
else
{
char *q = int_to_string( n / 10 );
char *p = int_to_string( n % 10 );
q = realloc( q, strlen( q ) + strlen( p ) + 2 );
strcat( q, " " );
return strcat( q, p );
}
}
char * int_to_string1( unsigned int n, char *s )
{
if( n < 10 )
{
char *p = "";
switch( n )
{
case 0:
p = "Zero";
break;
case 1:
p = "One";
break;
case 2:
p = "Two";
break;
case 3:
p = "Three";
break;
case 4:
p = "Four";
break;
case 5:
p = "Five";
break;
case 6:
p = "Six";
break;
case 7:
p = "Seven";
break;
case 8:
p = "Eight";
break;
case 9:
p = "Nine";
break;
}
return strcat( s, p );
}
else
{
strcat( int_to_string1( n / 10, s ), " " );
return int_to_string1( n % 10, s );
}
}
int main( void )
{
unsigned int n = 1234567890;
char *s = int_to_string( n );
puts( s );
free( s );
char s1[100];
s1[0] = '\0';
puts( int_to_string1( n, s1 ) );
}
The program output is
One Two Three Four Five Six Seven Eight Nine Zero
One Two Three Four Five Six Seven Eight Nine Zero