Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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 "?";
}
like image 746
Goda Pororu Avatar asked Dec 30 '25 04:12

Goda Pororu


2 Answers

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]
  :
    "?";
}
like image 113
edmqkk Avatar answered Dec 31 '25 19:12

edmqkk


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.

like image 26
Peter Avatar answered Dec 31 '25 17:12

Peter