I'm reading values from an input text file that I have no control over. The first line is an integer representing the number of the lines to follow. Each of those lines to follow contains one of 3 characters that can be found in the next enum:
enum Size {
S,
M,
L
}
The ifstream can't insert the value directly into a Size datatype. So the following code won't work to store all the values in a vector of the datatype Size
enum Size {
S,
M,
L
}
unsigned lines_count;
std::vector<Size> data;
file >> lines_count;
for (auto i = 0u; i < lines_count; i) file >> data[i]; // WRONG
So the values have to be stored into a char. I was wondering if there was a way to store the value into the datatype Size directly that RESEMBLES the following:
unsigned lines_count;
Size size;
char c;
file >> lines_count;
for (auto i = 0u; i < lines_count; i) {
file >> c;
size = Size::c // c resolves to either S, M, or L
data[i] = size;
}
I know that this syntax does NOT work. I just need the most concise way to do it instead of using a switch or if-statements.
CodePudding user response:
Enumerations have an underlying integral type with which the enumerators are represented. You can specify which integral value each enumerator should have explicitly. Since character literals are just integral values, you can specify them as well.
Then you can simply cast from any integral type to the enumeration type to get the enumerator corresponding to the integral value. This is not an implicit conversion and therefore requires an explicit static_cast
.
It does however not check in any way that the values are actually validly one of the enumerators. Especially if you go out-of-range of the enumeration range, you can cause undefined behavior if not checking beforehand or you could be using a value inside the range which doesn't match any of the enumerators. So you probably won't get around writing a function which manually checks the value anyway to have proper input validation.
I would also use a scoped enumeration since C 11. You can also explicitly specify that the underlying type shall be char
, then at least there are no range issues as mentioned above:
enum class Size : char {
S = 'S',
M = 'M',
L = 'L'
};
//...
file >> c;
// Does not validate that the value of c is one of the above!
data[i] = static_cast<Size>(c);