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?
Printable View
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
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
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;
}
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.