hey, I have a enum with many items, using cout, I only get the integers print out. what I want is the meaningful words in the enum. what is the idiom for this task?
hey, I have a enum with many items, using cout, I only get the integers print out. what I want is the meaningful words in the enum. what is the idiom for this task?
You can do that in Java because enums are class objects there, but enums in C/C++ are just souped up const ints, so if you print it, all you're going to get is a number. You'll have to write your own functions to print the names.
use strcpy
All problems in computer science can be solved by another level of indirection,
except for the problem of too many layers of indirection.
– David J. Wheeler
Printing enums as text requires that you translate the enum value into a string - and the compiler can not do that for you, which is pretty much the same as what cunnus88 said.
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
so this wont work?
Code:enum Category { unknown = -1, meat, poultry, seafood, dairy, vegetable, fruit, grain, sweet, nCategory };Code:void convertCategory(Category category, char categoryDescription[]) { switch (category) { case meat: strcpy(categoryDescription, "meat"); break; case poultry: strcpy(categoryDescription, "poultry"); break;
You could do that or we could make a C++ approach to the problem.
Code:#include <iostream> #include <string> #include <map> enum enWeapon { eWeaponSword = 0, eWeaponKnife = 1, eWeaponStick = 2 }; std::map<enWeapon, std::string> weaponMap; void InitializeMap() { weaponMap[eWeaponSword] = "Sword"; weaponMap[eWeaponKnife] = "Knife"; weaponMap[eWeaponStick] = "Stick"; } int main() { InitializeMap(); std::cout<<weaponMap[eWeaponStick]<<std::endl; std::cout<<weaponMap[eWeaponSword]<<std::endl; std::cin.get(); return 0; }
Woop?
I'd create a function and have the map be static variable, and make it initialize on the first function call. For more complex situations, where the map is needed by multiple functions, I'd create a class to do all things associated with that enum, including the enum itself.
It is too clear and so it is hard to see.
A dunce once searched for fire with a lighted lantern.
Had he known what fire was,
He could have cooked his rice much sooner.