Converting number to its alphabetic equivalent.

~s.o.s~ 0 Tallied Votes 183 Views Share

The program parses the digits in the number supplied to it and converts it to aplhabetical equivalent. Fore eg. input: 1234 output: one two three four This is a simple exercise for newbies, must try out. Tested and works under ideal input conditions.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    int digit = 0, count = 0, tmp = 0 ;
    long number = 0 ;
    char buffer [BUFSIZ] = { '\0' } ;
    const char* const mappings [] = { "zero", "one", "two", "three", "four", "five",
 "six", "seven", "eight", "nine" } ;

    printf ( "Enter the number: " ) ;
    fgets ( buffer, BUFSIZ, stdin ) ;

    int* my_digits = (int*) malloc ( sizeof (int) * strlen (buffer) ) ;
    number = atol ( buffer ) ;

    while ( number != 0 )
    {
        digit = number % 10 ;
        number /= 10 ;
        my_digits [count] = digit ;
        count ++ ;
    }

    printf ("\n\nThe representation : " ) ;

    while ( count > 0 )
    {
        tmp = my_digits [count - 1] ;
        fputs ( mappings[tmp], stdout ) ;
        putchar (' ') ;
        count -- ;
    }
    return 0 ;
}
Rashakil Fol 978 Super Senior Demiposter Team Colleague

Haskell version:

main = do putStr "Enter the number: "
          n <- readLn
          putStr "\n\nThe representation : "
          putStrLn . intercalate " " . map ((names !!) . digitToInt . show) $ n

names = [ "zero", "one", "two", "three", "four",
           "five", "six", "seven", "eight", "nine"]
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

In Javascript:

var input = "03857";
var arr = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
var output = input.replace(/(.)/g, function(a, b) {
    var i = parseInt(b); if(!isNaN(i)) return arr[i] + " "; else return "";
  });
print(output);

I'm sure we can come up with shorter and better constructs in modern programming languages but that's a moot point if you are asked to do it in C; show some mercy to those starting out with programming. :-)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.