1

Is it possible to have a string replace an integer. For example if you had a program that accepts a large integer like 23933, could you do something like:

int 2 = "two" int 3 = "three" int 9 = "nine"

So the output will read as follows:

"two three nine three three"

How would you go about doing this?

KThund
  • 49
  • 1
  • 3
  • 7
  • Using arithmetic operations (`/` and `%`), "split" the number digit by digit. Then, have some sort of mapping - digit<->word. You have 10 digits, so the mapping will not be that big. – Kiril Kirov Mar 14 '14 at 15:58
  • Thank you, both of your examples were helpful – KThund Mar 14 '14 at 16:31

2 Answers2

3
void printNum(int x)
{
    static const char * const num[] = {
        "zero ", "one ", "two "  , "three ", "four ",
        "five ", "six ", "seven ", "eight ", "nine "
    };

    if (x < 10) {
        printf(num[x]);
        return;
    }
    printNum(x / 10);
    printNum(x % 10);
}

Or the very tight version:

void printNum(int x)
{
    static const char * const num[] = {"zero ",  "one ", "two ", "three ",
                                       "four ",  "five ", "six ", "seven ",
                                       "eight ", "nine "};
    (x < 10)? printf(num[x]) : (printNum(x / 10), printNum(x % 10));
}
abelenky
  • 63,815
  • 23
  • 109
  • 159
1

With an array

const char *ints[] = {"zero", "one", "two", "three"};

int r = rand() % (sizeof ints / sizeof *ints);
printf("%s\n", ints[r]);
pmg
  • 106,608
  • 13
  • 126
  • 198