AhmedKh AhmedKh - 7 months ago 61
C++ Question

Enums and casting

This is my first time when it comes to casting and enums, so yea I came across this problem while trying to cast.

Assume I have the following enum

enum Region

and a function that reads a file that has a list of data

void loadData(castle &al3a, queue &q, float &c1, float &c2, float &c3)
int i = 0;
ifstream myfile;
int n = 0;
if (myfile.fail())
cout << "Error" << endl;
else {
string line;
while (!myfile.eof())
getline(myfile, line);
string line2;
int T_Health;
int T_Attack_N_Enemies;
int T_Fire_Power;

myfile >> T_Health >> T_Attack_N_Enemies >> T_Fire_Power;
getline(myfile, line2);
myfile >> c1 >> c2 >> c3;
getline(myfile, line2);
int a,b,c,d,e,f;
char g;
enemy x;
for (int i = 0; i < n - 3; i++)
myfile >> a >> b >> c >> d >> e >> f >> g;
x.ID = a;
x.type = static_cast<Type>(b);
x.time_step = c;
x.Health = d;
x.fire_power = e;
x.reload_power = f;
x.region = static_cast<Region>(g);
enqueue(q, x);
getline(myfile, line2);
for (int i = 0; i < 4; i++)
al3a.towers[i].Health = T_Health;
al3a.towers[i].attackEnemies = T_Attack_N_Enemies;
al3a.towers[i].firePower = T_Fire_Power;
al3a.towers[i].Tregion = (Region)i;
// shielded enemies have higher priority than ordinary enemies
/*Priority(Shielded Enemy) = C1 * (EnemyFirePower / EnemyDistance) + C2 / (EnemeyRemaining time to shoot + 1) + EnemyHealth * C3*/

the data file should look something like the photo uploaded.
each row represents an Enemy, the first column is the ID,the second is the type,third is time_step,fourth is Health,anyways the last one is the region.
the queue somehow is implemented successfully but when I try to
I end up getting 65 or 66.. etc pointing out to the ASCII code of A and B.. how do I cast the array to print out the A or B

P.S: type is also an enum with the same problem as the one stated prior

Picture: https://postimg.org/image/dqtftkya5/


If your char variable contains 'a', it does contain an ascii value (97). You should not be casting such value to enum unless you know what you are doing. Enums in C++ are usually stored on 8 bits (which is the same size as size of char) (I am not sure if this is standardized) so your x.region contains same value (ASCII) as your char g (that is why std::cout prints the ASCII value).

Doing enum cast is usually done only if your integral type is in enum's range (so if enum contains 4 elements, you should cast only integral values of range 0-3).

If you are interested in enum type behavior, you should look at this answer.

Moreover you should take a look at c++11 enum classes and this answer about mapping chars to enum class types, which might be what you are looking for.