0

I have the following syntax:

enum home
{
no,
yes,
}homew;

home homes;

std::string s;
s="no";

homes=s; //is not working. Why?

Were am I wrong?

sbi
  • 219,715
  • 46
  • 258
  • 445
sunset
  • 1,359
  • 5
  • 22
  • 35

6 Answers6

1

You are confusing strings with enumerated values.

An enum variable is simply an integer that you can use a literal for at compile time, nothing more than that.

It makes the code more understandable and self-documenting rather than merely using a number literal.

Blagovest Buyukliev
  • 42,498
  • 14
  • 94
  • 130
1
  1. This

    enum home { no, yes, } homew;
    

    defines the type home plus a variable homew of that type.
    Did you intent that? Why?

  2. The values defined for an enum type are literals, to be used as such:

    home homes = no;
    
  3. In C++ there's no built-in way to convert between enum value literals and a string representation of them. If you need this, you'll have to cook up your own.

Community
  • 1
  • 1
sbi
  • 219,715
  • 46
  • 258
  • 445
  • i did add homew at the end of enum home because otherwise i had errors. i couldn't say enum home{..}; home homes;. – sunset Jul 27 '11 at 08:02
0

enums in C++ are implicitly an int data type. You can't assign string values to enum.

Shamim Hafiz - MSFT
  • 21,454
  • 43
  • 116
  • 176
0

It doesn't compile because C++ provides no built-in mechanism for converting from std::string to an enum.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
0
typeof(home) != typeof(std::string) // types are not equal

Thus, you cannot assign an enum to std::string or otherwise. Implicit conversion between enum and integral types like bool, int etc. is possible however.

Is there a way I can solve my problem as it is?

If possible use std::map.

std::map<std::string, home> myTypes;
myTypes["yes"] = yes;
myTypes["no"] = no;

Now you can do,

homes = myTypes["no"];
iammilind
  • 68,093
  • 33
  • 169
  • 336
0

As others pointed out, enums values are of int type. You could instead write a small function that converts from enum to String like this:

std::string GetStringFromEnum(home iHome)
{
 switch (home)
 {
  case yes: return "yes";
  case no: return "no"; break;
  default: return "here be dragons";
 }
}

and vice-versa:

home GetEnumFromString(std::string iImput)
{
 if (iImput == "yes") return yes;
 return no; //if you extend the enum beyond 2 values, this function will get more complicated
}

and you could modify your code like so:

homes = GetStringFromEnum(no)

the downside for this approach is that if you modify the enum, you must also modify the convert function.

HTH,
JP

Ioan Paul Pirau
  • 2,733
  • 2
  • 23
  • 26