0

What I'm trying to do is have the user input a number, and then the program reads each digit back in word form. For example:

Input: 517

Output: Five One Seven

It's a simple command-line tool, using NSLogs and scanf to get the input and provide output, nothing too advanced. I have the jist of it, but it only works with one-digit numbers:

    #import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
    @autoreleasepool {

        int number;

        NSLog(@"Type your number.");
        scanf("%i", &number);


        if (number == 0) {
            NSLog(@"Zero");
        } else if (number == 1){
            NSLog(@"One");
        } else if (number == 2) {
            NSLog(@"Two");
        } else if (number == 3) {
            NSLog(@"Three"); 
        } else if (number == 4) {
            NSLog(@"Four");
        } else if (number == 5) {
            NSLog(@"Five");
        } else if (number == 6) {
            NSLog(@"Six");
        } else if (number == 7) {
            NSLog(@"Seven");
        } else  if (number == 8) {
            NSLog(@"Eight");
        } else if (number == 9) {
            NSLog(@"Nine");
        } 

    }
    return 0;
}

However, I'm having problems working with more digits. I was thinking of using something like this to split them up:

            right_digit = number % 10;
        NSLog(@"%i", right_digit);
        number /= 10;

But that would output backwards.

Any advice?

Thanks

Jtaylorapps
  • 5,680
  • 8
  • 40
  • 56
  • No, I'm going through a textbook on my own, trying to pick up on the Objective-C language more so than the applications in an iOS app – Jtaylorapps Mar 30 '12 at 02:13
  • An interesting tool that does more than this: https://helloacm.com/tools/convert-arabic-numerals-to-english-words/ – justyy May 07 '17 at 02:45

3 Answers3

1

Use Recursion

void printNumber(int a){
  if(a/10 > 0){
     printNumber(a/10);
  }

  int digit = a%10;
  switch(digit){
  {
    case 0:
       NSLog(@"Zero ");
       break;
    case 1:
       NSLog(@"One ");
       break;
    case 2:
       NSLog("Two ");
       break;
     ....
  }

}
Sunil Pandey
  • 7,042
  • 7
  • 35
  • 48
0

NSNumberFormatter has a styler that helps handle it for you.

NSNumberFormatter *numberFormatter = [[NumberFormatter alloc] init];
numberFormatter.numberStyle = NSNumberFormatterSpellOutStyle;
aug
  • 11,138
  • 9
  • 72
  • 93
0

So you create a list backwards then reverse it, and read the number to the user.

The user won't see any difference in terms of performance.

To do this with an array you can look at this question:

How can I reverse a NSArray in Objective-C?

Community
  • 1
  • 1
James Black
  • 41,583
  • 10
  • 86
  • 166