I have declared the following enum :
enum periods {one, five, ten, fifteen, thirty};
and now I want to pass it as a commandline argument
I have declared the following enum :
enum periods {one, five, ten, fifteen, thirty};
and now I want to pass it as a commandline argument in my main function.
periods mp = atoi(argv[2]); // simplified for answer...
So, there are several issues:
atoi
to the enum type... static_cast(...)
enum periods { one = 1, five = 5, ten = 10, fifteen = 15, thirty = 30 };
, but your example's obviously a little contrived so it's impossible to guess what will work best for your real needsYou're better off creating a function:
periods to_periods(const std::string& s)
{
if (s == "one") return one;
if (s == "five") return five;
if (s == "ten") return ten;
if (s == "fifteen") return fifteen;
if (s == "thirty") return thirty;
throw std::runtime_error("invalid conversion from text to periods");
}
(When there are more cases, it's not uncommon to use a std::map
or sorted std::vector
to track these associations, and it allows reusable algorithms and the same data to support conversions from enum numeric value to textual identifier.)