1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
|
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *make_words(char *s, int ncomma);
char *insert_comma(long n, int *ncomma);
char *int2words(int n);
int a;
int main(void)
{
printf("Enter number: ");
scanf("%d",&a);
printf("%d = %s\n",a,int2words(a));
getch();
return 0;
}
char *make_words(char *s, int ncomma)
{
int i, len, rest = 0;
char *p = NULL;
static char zzz[256];
static char *ones[] = {"one ","two ","three ","four ",
"five ","six ","seven ","eight ","nine "};
static char *tens[] = {"ten ","eleven ","twelve ","thirteen ",
"fourteen ","fifteen ","sixteen ","seventeen ","eighteen ","nineteen "};
static char *twenties[] = {"","twenty ","thirty ","forty ",
"fifty ","sixty ","seventy ","eighty ","ninety "};
static char *hundreds[] = {
"hundred ","thousand ","million "};
memset(zzz, '\0', 256); // fill with nulls
len = strlen(s);
for(i = 0; i < len; i++)
{
if ((p = strchr((s[i] == ',') ? &s[++i] : &s[i], ',')) == NULL)
{
p = &s[strlen(s)];
}
if (s[i] == '0')
{
continue; // skip one iteration
}
if ((rest = (p - &s[i])) != 0)
{
if (rest == 3)
{
strcat(zzz, ones[s[i] - '0' - 1]);
strcat(zzz, hundreds[0]);
if (len == 7 && s[2] == '0') strcat(zzz, hundreds[1]);
if (len == 11 && s[2] == '0') strcat(zzz, hundreds[2]);
}
else if (rest == 2)
{
if (s[i] == '1')
{
strcat(zzz, tens[s[++i] - '0']);
rest--;
}
else
{
strcat(zzz, twenties[s[i] - '0' - 1]);
}
}
else
strcat(zzz, ones[s[i] - '0' - 1]);
}
if (rest == 1 && ncomma != 0)
{
strcat(zzz, hundreds[ncomma--]);
}
}
return zzz;
}
char *insert_comma(long n, int *ncomma)
{
static char zzz[30];
int i = 0;
char *p = &zzz[sizeof(zzz)-1];
*p = '\0';
*ncomma = 0;
do
{
if (i % 3 == 0 && i != 0)
{
*--p = ',';
++*ncomma;
}
*--p = (char)('0' + n % 10);
n /= 10;
i++;
} while(n != 0);
return p;
}
char *int2words(int n)
{
int nc;
char *ps, *zzz, *minus;
char *buffer;
buffer = (char *) malloc(256);
// save any - sign
if (n < 0)
{
minus = "minus";
n = abs(n);
}
else
{
minus = "";
}
ps = insert_comma(n, &nc);
zzz = make_words(ps, nc);
sprintf(buffer,"%s %s", minus, zzz);
return buffer;
getch();
}
|