Goda Pororu
Goda Pororu

Reputation: 31

Is there a cleaner way to write this? (digit to string)

I made a number to digit converter, but it seems too verbose the way it is written. I seem some people talking about using a switch. Should I rewrite this with a switch or is there a better way to write it?

string numberToString(int n)
{
  if (n == 0)
    return "zero";
  if (n == 1)
    return "one";
  if (n == 2)
    return "two";
  if (n == 3)
    return "three";
  if (n == 4)
    return "four";
  if (n == 5)
    return "five";
  if (n == 6)
    return "six";
  if (n == 7)
    return "seven";
  if (n == 8)
    return "eight";
  if (n == 9)
    return "nine";
  else
    return "?";
}

Upvotes: 2

Views: 125

Answers (4)

Johannes Overmann
Johannes Overmann

Reputation: 5161

Short version:

std::string numberToString(int n)
{
    return (const char *[]){"zero", "one", "two", "three", "four", "five",
            "six", "seven", "eight", "nine", "?"}[unsigned(n) < 11 ? n : 10];
}

Upvotes: 1

Peter
Peter

Reputation: 36627

I wouldn't use a switch at all

std::string numberToString(int n) 
{
    const char *literal[] = {"zero", "one", "two", "three", "four", "five",
                           "six", "seven", "eight", "nine"};
    const char *no_result = "?";

    return std::string ( (n < 0 || n >= 10) ? no_result : literal[n]); 
}

The conversion in the return statement is optional (it happens implicitly) but I prefer to make it explicit.

The types of literal and no_result can be made to std::string if desired.

Upvotes: 5

Francis Cugler
Francis Cugler

Reputation: 7925

This would easily work and is very readable and reusable.

#include <string>
#include <vector>
#include <iostream>

class Converter {
private:
    const std::vector<std::string> numbers{ "zero", "one", "two", "three", "four",
                                            "five", "six", "seven", "eight", "nine", "?" };
public:
    std::string operator()( int n ) { 
        if ((n < 0) || (n > 10))
             return numbers.at(10);   
       return numbers.at(n); 
    }
};


int main() {
     Converter c;
     for ( int i = -5; i < 15; i++ )
         std::cout << c(5) << '\n';

     return 0;
}

-Output-

?
?
?
?
?
zero
one
two
three
four
five
six
seven
eight
nine
?
?
?
?
?
?

Upvotes: -3

edmqkk
edmqkk

Reputation: 356

Try using an array literal.

string numberToString(int n) {
  return (n >= 0 && n <= 9) ?
    (string[]){
      "zero",
      "one",
      "two",
      "three",
      "four",
      "five",
      "six",
      "seven",
      "eight",
      "nine",
    }[n]
  :
    "?";
}

Upvotes: 6

Related Questions