0

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 ;
}
2
Contributors
2
Replies
6
Views
10 Years
Discussion Span
Last Post by ~s.o.s~
0

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"]
0

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. :-)

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.