I have defined an enum like this:
enum eFeature
{
eF_NONE=0,
eF_PORT_A=1,
eF_PORT_B=2,
eF_PORT_C=3,
};
I would now like to convert a wstring (which is either "0", "1", "2" or "3") to eFeature.
I tried
eFeature iThis;
iThis = _wtoi(mystring.c_str());
But the compiler tells me "A value of type 'int' can not be assigned to an entity of the type eFeature."
Can somebody help?
Thank you.
You are attempting to assign an int to an enum, which is not allowed. Leaving the wstring distraction aside, what you are doing is the equivalent of
eFeature iThis;
iThis = 42;
You first need to cast the int to the enum type:
eFeature iThis;
iThis = static_cast<eFeature>(42);
Obviously, you would need to perform some kind of range checking first.
Related
I am using the ldap_modify function to change an attribute value using C++ ...
msgid=ldap_modify_ext_s( ld, dnNameval, ldapmod,NULL,NULL );
The problem is the mod_val argument in that function ...
LDAP *id;
dnNameval ="distinguised name";
In the ldapmod there are three values ...
mod_type="attribute to be changed";
mod_op=LDAP_MOD_REPLACE;
ldapmod struct
The ldapmod struct is:
typedef struct ldapmod {
int mod_op;
char *mod_type;
union {
char **modv_strvals;
struct berval **modv_bvals;
} mod_vals;
#define mod_values mod_vals.modv_strvals
#define mod_bvalues mod_vals.modv_bvals
} LDAPMod;
I tried passing the value like this:
mod_vals=(PWCHAR*){"bala",Null};
which resulted in the error
error C2679: binary '=' : no operator found which takes a right-hand operand
of type 'PWCHAR *' (or there is no acceptable conversion)
I also tried this:
mod_vals.modv_strvals=(PWCHAR*) Password1;
mod_vals.modv_bvals=NULL;
but then the array has a null value...
Can anyone help me work out how to pass the values in that variable? Do I need to include any additional header files? I am already using the winldap.h header.
Thanks in advance.
This won't work:
mod_vals = (PWCHAR*){"bala",Null};
You can't assign a value to a union that way. You have to specify which of the members of the union you want to write to. Also, (PWCHAR *) is the wrong type; you're not dealing with wide characters. Even if you were, you can't convert a string just by casting it.
This won't work either:
mod_vals.modv_strvals=(PWCHAR*) Password1;
mod_vals.modv_bvals=NULL;
The modv_strvals member is a pointer-to-pointer, not just a pointer, and it doesn't make sense to write to two members of a union; they're mutually exclusive. Depending on context you either use modv_strvals or modv_bvals, never both.
You probably want to do this:
mod_vals.modv_strvals = {"bala", Null};
The struct is as follows:
struct padData
{
enum buttonsAndAxes
{
select,
start,
ps
};
};
The object of the struct:
padData pad;
I am accessing this enum as follows:
printf ("\n%d", pad.buttonsAndAxes[0]);
Error:
error: invalid use of ‘enum padData::buttonsAndAxes’
Then, I tried:
printf ("\n%d", pad::buttonsAndAxes[0]);
Error:
error: ‘pad’ is not a class or namespace
Now what? Please guide.
Compiler: gcc version 4.5.0
EDIT 1:____________________________________
printf ("\nemit: %d", padData::(select)0);
results in:
error: expected unqualified-id before ‘(’ token
My aim is to fetch the word "select" through its value 0. How to achieve that? Also, is the word "select" a string?
The enum values become names in the scope of the class. So you would use padData::select from outside the class, or just select from inside the class.
In C++11 you can qualify the enumerators with the name of the enum, giving padData::buttonsAndAxes::select from the outside and buttonsAndAxes::select from inside.
Printing the name of an enumerator is not easily done in C++, because the names are gone after compilation. You need to set up a table mapping the values to their strings by hand. If you don't supply explicit values like in your example, you can simply use an array:
enum buttonsAndAxes
{
select,
start,
ps
};
const char* buttonsAndAxesNames[] = {
"select",
"start",
"ps"
};
And then you index into that array:
printf("%s", buttonsAndAxesNames[select]);
If you want some more sophisticated approach, you can find a bunch of tricks in previous questions.
printf ("\n%d", padData::select);
Enum is not array, it is used without index.
ENUMS are mainly used for better readability of code rather than calculation facilitators. ENUMS are mainly literals which are assigned values 0,1,2 etc unless specified otherwise. So you should always use them with "::" qualification rather than as array
You seem to need a good C++ book.
Enumerations, in C and C++, are a convenient way to:
map an integral value to a "smart" name
group together values that belong together
The syntax is quite simple (in C++03):
enum <enum-name> {
<value-name-0> [= <value-0>],
<value-name-1> [= <value-1>],
...
};
Where:
<enum-name> is the name of the type that is introduced
<value-name-X> is the name of a value of the enum
<value-X> is the value given to the name, and is optional
If no value is given to a name:
if it is the first, it is set to 0
else, it is set to the value of the previous name, + 1
Here is a small example demonstrating the use of enums:
enum Color {
Blue,
Green,
Red
};
char const* name(Color c) {
switch(c) {
case Blue: return "Blue";
case Green: return "Green";
case Red: return "Red";
}
assert(0 && "Who stored crap in my enum ?");
}
This illustrates a few important points at once:
Color is a type, like a struct type or a class type. It can be typedefed and all.
an enum "value-name" is an integral constant, it can be used as template parameter or in switch cases.
an enum "value-name" is injected in the scope in which the type is declared, and not nested within. (C++11 allows to scope the values with the enum class syntax)
something else entirely could be stored in the enum, while this should not happen in well behaved applications, you can do it through casting...
What is not shown, is that an enum is under the hood a plain integer. The exact underlying type though is determined at the discretion of the compiler. There are a few rules in this choice, that should not matter to you, all you should know is that the type chosen is wide enough to contain all the values of the enum (and possibly signed if required). What it implies is that the type chosen is not necessarily a plain int.
Therefore: printf("%d", Green); is a programming error. It should be printf("%d", (int)Green);.
Another important point, is that enum names do not appear in the final binary. The names are substituted for their values directly, no runtime overhead at all. Debuggers typically retrieve the names from the debug information (if available) and substitute them back in when presenting the information to you.
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?
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.
This
enum home { no, yes, } homew;
defines the type home plus a variable homew of that type.
Did you intent that? Why?
The values defined for an enum type are literals, to be used as such:
home homes = no;
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.
enums in C++ are implicitly an int data type. You can't assign string values to enum.
It doesn't compile because C++ provides no built-in mechanism for converting from std::string to an enum.
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"];
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
I have an enum that I'm doing a cout on, as in: cout << myenum.
When I debug, I can see the value as an integer value but when cout spits it out, it shows up as the text representation.
Any idea what cout is doing behind the scenes? I need that same type of functionality, and there are examples out there converting enum values to string but that seems like we need to know what those values are ahead of time. In my case, I don't. I need to take any ol' enum and get its text representation. In C# it's a piece of cake; C++.. not easy at all.
I can take the integer value if I need to and convert it appropriately, but the string would give me exactly what I need.
UPDATE:
Much thanks to everyone that contributed to this question. Ultimately, I found my answer in some buried code. There was a method to convert the enum value to a string representing the actual move like "exd5" what have ya. In this method though they were doing some pretty wild stuff which I'm staying away form at the moment. My main goal was to get to the string representation.
Enum.hpp:
enum Enum {
FOO,
BAR,
BAZ,
NUM_ENUMS
};
extern const char* enum_strings[];
Enum.cpp:
const char* enum_strings[] = {
"FOO",
"BAR",
"BAZ",
"NUM_ENUMS",
0 };
Then when I want to output the symbolic representation of the enum, I use std::cout << enum_strings[x].
Thus, you do need to know the string values, but only in one place—not everywhere you use this.
This functionality comes from the IOStreams library. std::cout is an std::ostream.
std::stringstream is an std::ostream too.
int x = 5;
std::stringstream ss;
ss << x;
// ss.str() is a string containing the text "5"
I have an external tool which is generating an ENUM based on user inputs. Now this ENUM is being used by my C++ code where in i have to select a particular ENUM based on a variable say 'x'. The ENUMS generated are of the form 'ENUM_1', 'ENUM_2', 'ENUM_3'....so on. Now I want the code inside my code such that the appropriate ENUM is chosen based on 'x'. I tried using the strcat function like:
typedef enum ( enum_1, enum_2, enum_3...enum_n) map1;
y=(map1)strcat("enum_", x);
but it gives me the error "Cannot convert from char* to map1.
Can someone pls suggest a method of achieving this.
ThankYou
You can't do this using strcat. From the description what I understand is that you want to convert x to map1. To achieve this, you can do map1 m = (map1)(x-1); See this sample code:
typedef enum { enum_1, enum_2, enum_3} map1;
int main()
{
int x = 1;
map1 m = (map1)(x-1);
}
-1 is required because, the integer value of the enums in map1 starts from 0.
You can't do this. Well you can't do it this way...
Enums aren't evaluated by name at compile time. You'll have to try something with the preprocessor. You can create a define to do something similar. Something like:
#define fn(x) enum_##x
And then call
fn(x)
But this happens when the file gets preprocessed. So you can't access runtime variables. Judging by your code I don't think you'll be able to do what you want.
Good luck though.
Now I want the code inside my code such that the appropriate ENUM is chosen based on 'x'.
Enumerated values are constants and based on the statement I assume that x is an integer data type.
y=(map1)strcat("enum_", x);
strcat(..) passing parameters should be of type char*. And clearly x is not of type char* based on previous statement. It not clear why are you using strcat for achieving this task.
Answer for your subject line: No. You cannot use strcat with enumerated values.