Reputation: 11
i'm a begginer in c++ and I need to make some automobile related classes that need to be read from a file.In one of them I want to use an enum my class looks like this:
enum engines{ gasoline, hybrid, diesel };
class Automobil
{
const int id;
char *model;
engines engine;
int max_speed;
int engine_cc;
float avg_consumption_urban;
float avg_consumption;
float avg_speed_urban;
float avg_speed;
}
and i need to overload the >> operator to read the object from a file but when I do it for the engine,I have errors. How do I still keep the enum and read from the file?
friend ifstream& operator>>(ifstream& input, Automobil &a)
{
delete[] a.model;
input >> a.model;
input >>a.engine; //error here
input >> a.max_speed;
input >> a.engine_cc;
input >> a.avg_consumption_urban;
input >> a.avg_speed_urban;
input >> a.avg_consumption;
input >> a.avg_speed;
return input;
}
Upvotes: 0
Views: 2137
Reputation: 57753
There is no overloaded form of operator>>
to read in enumerations.
You have two choices:
I prefer using the name method. Read in the name as a string, and look up in a table of [name, enum], to convert it.
Edit 1: An implementation
std::map<std::string, enum engines> conversion_table;
// Initialization
conversion_table["gasoline"] = engines::gasoline;
conversion_table["hybrid"] = engines::hybrid;
conversion_table["electric"] = engines::electric;
Note: you may have to remove engines::
from the values.
To convert text to enum:
engines engine_type = conversion_table[text];
Upvotes: 3