0

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;

}
Barmar
  • 741,623
  • 53
  • 500
  • 612

1 Answers1

3

There is no overloaded form of operator>> to read in enumerations.

You have two choices:

  1. Read in enumeration name and convert to the enum class.
  2. Read in enumeration value (number) and convert to enum class.

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];
Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154