You could add a conversion function to your enum
such as this:
enum direction_t
{
dir_n = 0,
dir_ne = 1,
dir_e = 2,
dir_se = 3,
dir_s = 4,
dir_sw = 5,
dir_w = 6,
dir_nw = 7,
dir_up = 8,
dir_down = 9,
dir_invalid = 10
bool str_to_dir (std::string dir, direction_t &out_dir) // do not use const reference here!
{
std::for_each(data.begin(), data.end(), [](char & c) {
c = ::tolower(c);
});
if (dir == "north" || dir == "n") // add whatever here!
{
out_dir = dir_n;
}
else if (dir == "northeast" || dir == "ne")
{
out_dir = dir_ne;
}
...
else
{
out_dir = dir_invalid;
return false;
}
return true;
}
};
void do_stuff (const std::string &input)
{
std::vector split;
// split string using your function
if (split.size() == 2 && split[0] == "go")
{
direction_t dir;
if (direction_t::str_to_dir(split[1], dir))
{
uint8_t index = (uint8_t)dir; // cast your direction to an index between 0 and 9, see direction_t
some_array[index]->function_call();
}
else
{
// dir_invalid returned...
}
}
}
You can add functions to enum
and struct
just as in class (but without a keyword, everything is marked public
instead of private
). This way you can add all the parsing to your enum routine and get a direction_t
from it and as you have predefined the values, if the function returns true
your can convert your enum
type to in integer type and use it as an array as you know by returning true that it is a valid direction.
Also note that its important that C++ is case sensitive, hence converting the whole string to lowercase to mitigate that and only having to check agains lowercase strings.
If you only want to check against a single string instead of multiple per direction, you can do something like this:
enum direction_t
{
dir_n = 0,
dir_ne = 1,
dir_e = 2,
dir_se = 3,
dir_s = 4,
dir_sw = 5,
dir_w = 6,
dir_nw = 7,
dir_up = 8,
dir_down = 9,
dir_invalid = 10
};
int convert_str_to_index(std::string dir)
{
static const std::pair<std::string, uint32_t> dir_conversion_array[] = {
std::make_pair("north", dir_n),
std::make_pair("northeast", dir_ne),
std::make_pair("east", dir_e),
std::make_pair("southeast", dir_se),
std::make_pair("south", dir_s),
std::make_pair("southwest", dir_sw),
... // add everything here...
};
std::for_each(data.begin(), data.end(), [](char & c) {
c = ::tolower(c);
});
for (int i = 0; i < 10; ++i)
{
if (dir_conversion_array[i].first == dir)
{
return i;
}
}
return -1;
}
void do_stuff (const std::string &input)
{
std::vector split;
// split string using your function
if (split.size() == 2 && split[0] == "go")
{
int index = convert_str_to_index(split[1]);
if (index >= 0)
{
some_array[index]->function_call();
}
else
{
// dir_invalid returned...
}
}
}