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 "?";
}
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]
:
"?";
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With