简体   繁体   中英

C - Trying to convert an unspecified amount of digits entered into their respective individual words

I know this is somewhat similar to the program that converts digits to words using things like "Thousands", "Hundred", etc. However, I'm looking to take an integer of any size (such as 543210) and create an output of "Five Four Three Two One Zero". I'm using a switch statement that I think I understand fully and have working. I am stuck on using some sort of loop to single out each digit of the integer and print its word, then repeat for the next digit, and the next. I am fairly new at all this so any help would be appreciated! Thanks.

Here's what I have so far (Not much, but I'm stuck on where to go with a loop):

#include <stdio.h>

int main(void)
{
        int num;

        printf("Please enter an integer: \n");
        scanf("%d", & num);

        while (num==0)
        {
        switch (num)
        {
                case (0):
                        printf("Zero ");
                        break;
                case (1):
                        printf("One ");
                        break;
                case (2):
                        printf("Two ");
                        break;
                case (3):
                        printf("Three ");
                        break;
                case (4):
                        printf("Four ");
                        break;
                case (5):
                        printf("Five ");
                        break;
                case (6):
                        printf("Six ");
                        break;
                case (7):
                        printf("Seven ");
                        break;
                case (8):
                        printf("Eight ");
                case (8):
                        printf("Eight ");
                        break;
                case (9):
                        printf("Nine ");
                        break;
                case (10):
                        printf("Ten ");
                        break;

        }
        }
        return 0;

}

so you can try reading a string with fgets and looping until the end of the string (or like in my example code, until the end of digits) and print names of digits.

#include <stdio.h>

char *names[10] = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", };
int main()
{
    char buffer[500] = {0};
    int i = 0;
    fgets(buffer, sizeof(buffer), stdin);
    while (isdigit(buffer[i]))
        printf("%s ", names[buffer[i++] - '0']);

    return 0;
}

http://ideone.com/Ba7Rs3

The easiest way to do this is to consume the digits from the right-hand side using integer division "/" & "%".

Here's some partial code:

int digit;
//start a loop
//if num > 10
digit = num % 10;
num = num / 10;
//else
digit = num;
//break the loop

That will print the numbers from right to left. If you want left to right, you could make a recursive function that if num > 10, calls itself with the parameter of num / 10, and then prints the digit value.

Edit: Here's an example of your recursive function:

void convertToWords (int num){
    if (num > 10){
        convertToWords(num / 10);
    int digit = num % 10;
    //your switch statement to print the words goes here
}

One possible approach:

#include <stdio.h>

char *digits[10] = {
  "Zero", "One", "Two", "Three", "Four",
  "Five", "Six", "Seven", "Eight", "Nine"
};

int main() {
  int num, digit; 
  long long tenth = 1;
  printf("Please enter an integer: \n");
  scanf("%d", &num);

  while (tenth < num) {
    tenth *= 10;
  }

  while (tenth > 1) {
    tenth /= 10;
    digit = num / tenth;
    num %= tenth;
    printf("%s ", digits[digit]);
  }
  return 0;
}

Demo . Now for explanations:

First and foremost, it makes little sense to use switch here: digits are pretty darn linear by their nature, therefore their names can (and should) be stored in an array of strings instead ( char *digits[10] in this code). Then you'll be able to get a label for a particular digit just by accessing this array using this digit as an index.

Second, the key problem of this program is extracting each digit from the input separately. It's easier to do going from right to left (take the result of number % 10 , assign number / 10 to number , repeat), but here things should be done in another way - left to right. So this is what we do:

  • calculate tenth - the first power of 10 that's bigger than the given number (for example, if we work with 546, that'll be 1000)
  • at each subsequent iteration:

-- divide tenth by 10

-- process the result of integer division of number by tenth

-- assign back to number the remainder of number divided by tenth

At the first iteration tenth becomes 100 (1000/10), 546/100 gives you 5 (an integer divided by integer is integer, decimals are truncated), 546 % 100 gives you 46 - that's stored as a number for the second iteration.

At the second iteration tenth becomes 10 (100/10), 46/10 gives you 4, 46 % 10 gives you 6. Next cycle: 10/10 => 1, 6/1 => 6, 6%1 => 0. So tenth has become equal to 1, and loop is stopped - as all the digits are processed.

The most understandable way IMO (if not the most efficient) uses powers of ten. If we start with the number 543210 , then the number of digits is given by log10(543210) + 1 = 6. Then

// start with a number
int num = 543210;
// how many digits?
int digits = log10(num) + 1; // 6
// now loop through each digit
for (int i = digits - 1; i > 0; --i) {
  int p = (int)pow(10, i);
  int digit = (num / p) % 10; // we want integer division
  switch (digit) { ... }
}

(Remember to #include <math.h> .)

A no limit solution inspired by @Hayri Uğur Koltuk

#include <ctype.h>
#include <stdio.h>
int main() {
  int ch;
  while (((ch = getc(stdin)) != EOF) && (isdigit(ch))) {
    static const char *Digit[10] = { "Zero", "One", "Two", "Three", "Four",
        "Five", "Six", "Seven", "Eight", "Nine" };
    printf("%s ", Digit[ch - '0']);
  }
  puts("\n");
  return 0;
}

A simple recursive solution

static void PrintDigit(unsigned n) {
  static const char *Digits[10] = {
    "Zero", "One", "Two", "Three", "Four",
    "Five", "Six", "Seven", "Eight", "Nine" };
  if (n > 9) {
    PrintDigit(n/10);
  }
  printf("%s ", Digits[n%10]);
}

void PrintDigits(unsigned n) {
  PrintDigit(n);
  printf("\n");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM