Skip to content

Instantly share code, notes, and snippets.

@Experiment5X
Created August 27, 2013 20:52
Show Gist options
  • Save Experiment5X/6359017 to your computer and use it in GitHub Desktop.
Save Experiment5X/6359017 to your computer and use it in GitHub Desktop.
A simple program that will convert a string of numbers to the word equivalent. For example, if the user enters 12345 the program will output One, Two, Three, Four, Five. Be careful with this, there isn't a check to ensure the input buffer doesn't overflow.
#include <stdio.h>
#include <string.h>
#define CHAR_TO_INT(c) (c - 0x30)
int IsValidPhoneNumber(char *phoneNumber, int length)
{
for (int i = 0; i < length; i++)
if (CHAR_TO_INT(phoneNumber[i]) < 0 || CHAR_TO_INT(phoneNumber[i]) > 9)
return -1;
return 0;
}
int PhoneNumberToString(char *phoneNumber, int length)
{
const char *numberWords[10] = { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" };
int outBuffIndex = 0;
// make sure that the phone number the user entered is valid
if (IsValidPhoneNumber(phoneNumber, length) != 0)
return -1;
// print out the word equivalent for each digit in the phone number
for (int i = 0; i < length; i++)
printf("%s, ", numberWords[CHAR_TO_INT(phoneNumber[i])]);
// remove the the trailing ", "
printf("\b\b \n");
// it was successful
return 0;
}
int main()
{
char phoneNumber[20] = { 0 };
// get the phone number from the user
printf("Phone Number: ");
scanf("%s", phoneNumber);
// if the conversion fails, then the phone number was invalid
if (PhoneNumberToString(phoneNumber, strlen(phoneNumber)) == -1)
printf("Invalid phone number.\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment