[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 564
  • Last Modified:

C++ enum question

enum color_type {red, orange, yellow, green, blue, violet};
 color_type shirt, pants;
 shirt = red; pants = blue;

 cout << shirt << " " << pants << endl;

In the above snippet of code, the cout statement outputs the numeric values of 'red' and 'blue'.

But IS there any way that I can print the actual values 'red' and 'blue' without using an if then else
for example...

   if (shirt== red) cout << "red";
   if (shirt == blue) cout << "blue" ;

 and so on.
0
prain
Asked:
prain
  • 3
  • 3
  • 3
  • +6
1 Solution
 
B1-66ERCommented:
Hi prain.

>>without using an if then else

Yes, you can use swith operator

switch(shirt)
{
 case red: cout << "red"; break ;
 case blue: cout << "blue"; break ;
}
0
 
rahul_r_jadhavCommented:
you can make any array
char* colors[] =  {"red", "orange", "yellow", "green"," blue", "violet"};
and use
cout << colors[red] <<endl;
0
 
DrAskeCommented:
you can do this ..

char*colorName[] = {"red", "orange", "yellow", "green","blue","violet"};
cout<<colorName[(int)shirt]<<endl;
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
DrAskeCommented:
:) I didn't refresh .. sorry ..
0
 
prainAuthor Commented:
Ok, so you need to have a corresponding array or rather hard code the actual values dependeing on the item selected.

Does'nt C++ have some other way such as overlorded << and >>  operators to do this?
0
 
rahul_r_jadhavCommented:
I think to overload an operator we need atleast one parameter which is class and enum is a basic data type. So we will not be able to overload it.
0
 
List244Commented:
An enum is not the right tool for what you are doing, you could try:

#include <map>
#include <iostream>

using namespace std;

int main()
{
      map <const char*,char *> color_type; // create our color type
      color_type["Red"] = "red";
      color_type["Orange"] = "orange";
      color_type["Yellow"] = "yellow";
      color_type["Green"] = "green";
      color_type["Blue"] = "blue";
      color_type["Violet"] = "violet";//finished adding colors and values
      char *shirt, *pants;//create out pants and shirts
      shirt = "Red";//set shirt color
      pants = "Blue";//set pant color
      cout << color_type[shirt] << " " << color_type[pants] << endl; //display
}
0
 
rahul_r_jadhavCommented:
I am not sure if this will help.....
if we get "Red" in shirt then why do we need to go again to map and get the value as "Red"??
0
 
DrAskeCommented:
Exactly?? 'cause you can print it :
cout<<shirt<<endl;
output:
Red
0
 
List244Commented:
Haha, you are right about that, how about this:

#include <map>
#include <iostream>

using namespace std;

enum color_type {red=1, orange, yellow, green, blue, violet};

int main()
{
      map <int,char *> color_type; // create our color type
      color_type[1] = "red";
      color_type[2] = "orange";
      color_type[3] = "yellow";
      color_type[4] = "green";
      color_type[5] = "blue";
      color_type[6] = "violet";//finished adding colors and values
      int shirt, pants;//create out pants and shirts
      shirt = red;//set shirt color
      pants = blue;//set pant color
      cout << color_type[shirt] << color_type[pants];
}

Though, that is almost the same as the array method, it does solve the "hard coded" problem without having
to use new and such for resizing.  Which means you can throughout your program add colors, while still being
able to use your enum for accessing your base-colors by color name rather than ID number.

However, if you do not need to be adding while the program runs, then there should be no problem with hardcoded
values.
0
 
steveiamCommented:
Even if you could overload << to print it out, you would still need to use one of the techniques above (switch, array, etc.) to turn it from the enum value into a string to output.
0
 
Knut HunstadCommented:
I have made a class to try to accomplish something similar for using enums in dialog boxes. I got it working, but then never got time to really polish the solution. So here it is, and any comments are welcome! I'm sure there are other similar solutions out there, but I tried searching before I made this, without finding anything I liked. It's used like this:

// MyEnums.h
#include "CEnum.h"
enum color_type {red=0, orange, yellow, green, blue, violet};
typedef CEnum<6, red, IDS_RED, IDS_ORANGE, IDS_YELLOW, IDS_GREEN, IDS_BLUE, IDS_VIOLET> CColor; // Color names are put into string resources
// Make sure somehow that the below is included exactly once. I haven't found any way around this.
#ifdef _CCOLOR_ENUMS_DEFINE
long CColor::m_NameId[CColor::Count];
#endif

//MyEnums.cpp
// Define this only in this file
#define _CCOLOR_ENUMS_DEFINE
#include "MyEnums.h"
CColor shirt, pants;
shirt = red;
pants = green;
cout << shirt.Name() << " " << pants.Name() << " " << CColor::Name(green) << endl;

With a proper << overload in CEnum, you should be able to do:

CColor shirt, pants;
shirt = red;
pants = green;
cout << shirt << " " << pants << endl;

and here is the class:

// CEnum.h
template <int N, int D, long R1, long R2=-1, long R3=-1, long R4=-1, long R5=-1, long R6=-1, long R7=-1> class CEnum {
public:
   CEnum(int i=D) : m_Type(i) {
      m_NameId[0] = R1;
      if (N>1)
         m_NameId[1] = R2;
      if (N>2)
         m_NameId[2] = R3;
      if (N>3)
         m_NameId[3] = R4;
      if (N>4)
         m_NameId[4] = R5;
      if (N>5)
         m_NameId[5] = R6;
      if (N>6)
         m_NameId[6] = R7;
   };
   CString Name() {
      return Name(m_Type);
   };
   static CString Name(const int i) {
      return CString((LPCTSTR) NameId(i));
   };
   inline long const NameId() {
      return m_NameId[m_Type];
   };
   static inline long const NameId(int i) {
      return m_NameId[i];
   };
/* Include this part if you want to use enums in dialog box lists
   void SetComboBox(CDataExchange* pDX, int nIDC) {
      CComboBox* pComboBox((CComboBox*) pDX->m_pDlgWnd->GetDlgItem(nIDC));
      if (!pComboBox)
         return;
      pComboBox->ResetContent();
      for (int i=0; i < Count; i++) {
         CString sTmp(Name(i));
         pComboBox->AddString(Name(i));
      }
      DDX_CBIndex(pDX, nIDC, m_Type);
   };
   void SetComboBox(CDataExchange* pDX, CComboBox& ctlComboBox, int nIDC) {
      DDX_Control(pDX, nIDC, ctlComboBox);
      ctlComboBox.ResetContent();
      for (int i=0; i < Count; i++) {
         CString sTmp(Name(i));
         ctlComboBox.AddString(Name(i));
      }
      DDX_CBIndex(pDX, nIDC, m_Type);
   };
   void ReadComboBox(CDataExchange* pDX, int nIDC, CDocument* pDocument) {
      int iOldValue=m_Type;
      DDX_CBIndex(pDX, nIDC, m_Type);
      if (iOldValue != m_Type)
         pDocument->SetModifiedFlag();
   };
*/
   inline operator int() { return m_Type; };
   CEnum<N,D,R1,R2,R3,R4,R5,R6,R7>& operator=(const int i) {
      m_Type = i;
      return *this;
   };
   static const int Count=N;
   static long m_NameId[N];
protected:
   int m_Type;
};
0
 
Deepu AbrahamR & D Engineering ManagerCommented:
Try this:

enum color_type {red=0, orange, yellow, green, blue, violet};
char*colorName[] = {"red", "orange", "yellow", "green","blue","violet"};

cout<<colorName[red] <<endl;
cout<<colorName[orange]<<endl;
cout<<colorName[yellow] <<endl;
cout<<colorName[green] <<endl;
cout<<colorName[blue]<<endl;
cout<<colorName[violet] <<endl;

Best Regards,
Deepu
 
0
 
List244Commented:
Deep, that exact solution was given by DrAske and Rahul please read offered solutions before posting your answer.
0
 
Deepu AbrahamR & D Engineering ManagerCommented:
Sorry pal, I thought no one explained about mapping enum or passing enum value in the colorName[] array.

Best Regards,
Deepu
0
 
cupCommented:
Try this - macro lovers will love it, macro haters will hate it

colour.h
CLR(red),
CLR(orange),
CLR(yellow),
CLR(green),
CLR(blue),
CLR(violet)

In your code

// Define the strings
#define CLR(x) #x,
char* colourName[] = {
#include "colour.h"
};
#undef CLR

// Define the enums
#define CLR(x) x
enum colourtype {
#include "colour.h"
};
#undef CLR

cout  << colourName[shirt] << endl;

The good thing about this is that  you can add more colours or rearrange them and all the relevant parts of code will readjust themselves accordingly.  You only have to do it in one place.
0
 
prainAuthor Commented:
All,

Thanks for all these different versions you all have submitted here. But I had to go buy the method that suits me the best. Even though it may not be the best, I selected List244's method to go about with my work.

Thanks
prain.
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 3
  • 3
  • 3
  • +6
Tackle projects and never again get stuck behind a technical roadblock.
Join Now