Last active
August 24, 2024 20:53
-
-
Save dakka/b93ff6ee9e7a8d42f35a9f79d612868d to your computer and use it in GitHub Desktop.
Create C++ source for an enum class with named numbers. 0 based.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <string_view> | |
#include <vector> | |
#include <sstream> | |
#include <array> | |
#include <cstdlib> | |
constexpr std::array ones {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"}; | |
constexpr std::array teens {"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}; | |
constexpr std::array tens {"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"}; | |
std::string num2words(int number) | |
{ | |
if (number == 0) | |
return ones[0]; | |
std::ostringstream words; | |
if (number >= 1000000) | |
{ | |
words << num2words(number / 1000000) << "_million"; | |
if (number %= 1000000) | |
words << '_'; | |
} | |
if (number >= 1000) | |
{ | |
words << num2words(number / 1000) << "_thousand"; | |
if (number %= 1000) | |
words << '_'; | |
} | |
if (number >= 100) | |
{ | |
words << ones[number / 100] << "_hundred"; | |
if (number %= 100) | |
words << '_'; | |
} | |
if (number >= 20) | |
{ | |
words << tens[number / 10]; | |
if (number %= 10) | |
words << '_'; | |
} | |
if (number > 10 && number < 20) | |
words << teens[number - 11]; | |
else if (number > 0) | |
words << ones[number]; | |
return words.str(); | |
} | |
int main(int argc, char *argv[]) | |
{ | |
const std::vector<std::string_view> args{argv, argv + argc}; | |
if (args.size() < 3) | |
{ | |
std::cerr << "Usage: " << args[0] << " <classname> <count> [<prefix>]\n"; | |
return 1; | |
} | |
bool has_prefix { args.size() >= 4 }; | |
int number{}; | |
try | |
{ | |
if ((number = std::stoi(args[2].data())) <= 0) | |
{ | |
std::cerr << "<count=" << number << "> must be > 0\n"; | |
return 1; | |
} | |
} | |
catch(const std::exception& e) | |
{ | |
std::cerr << "exception: invalid count: " << e.what() << '(' << args[1] << ")\n"; | |
return 1; | |
} | |
std::cout << "enum class " << args[1] << "\n{\n "; | |
for (int ii{}; ii < number; ++ii) | |
{ | |
if (ii) | |
{ | |
std::cout << ", "; | |
if (ii % 5 == 0) | |
std::cout << "\n "; | |
} | |
if (has_prefix) | |
std::cout << args[3] << '_' << ii; | |
else | |
std::cout << num2words(ii); | |
} | |
std::cout << "\n};\n"; | |
return 0; | |
} | |
Author
dakka
commented
Aug 20, 2024
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment