0

How to write an array using enum in c++

https://code.sololearn.com/cYGTR71vuBBt/?ref=app I tried doing this code but I can't get my expected result. how do I write its source code ?

7th Dec 2017, 3:35 PM
Hana Ken
Hana Ken - avatar
1 Respuesta
+ 1
Why? Enums are just a bunch of integers below the hood. The only way to write them to an array is to write them yourself like: enum X { A,B,C,D,E }; int arr[ 5 ] = { A, B, C, D, E }; Since an enum starts at 0, this is the same as doing int arr[ 5 ] = { 0, 1, 2, 3, 4 }; They are NOT strings, so what you are doing ( or trying to ) is not possible like that. You could however use a translation function, usually implemented with a switch: #include <iostream> enum X { A,B,C,D,E }; std::string XtoString( X i ) { switch( i ) { case A: return "A"; case B: return "B"; case C: return "C"; // etc... } } #define x(i) XtoString(i) int main() { std::string arr[ 3 ] = { x(A), x(B), x(C) }; for( auto i: arr ) std::cout << i << std::endl; } You may want to rethink some things ^^
7th Dec 2017, 5:02 PM
Dennis
Dennis - avatar