I'm studying enumeration at the minute and i've a quick question. In the following code using enum, are you limited to ouputting the sequence number of the possible values, or can you use the enum operator to output the text "green"?

#include <iostream>
#include <sstream>
#include <fstream>
#include "conio.h"
using namespace std;

int main()
{	
	enum colour {red, green, blue};
	colour favourite;
	favourite = green;

	cout << favourite;

	_getch();
}

That's a new one 'enum operator'. What's that?

Do you mean something like below?

#include <iostream>

enum colour {red, green, blue};

std::ostream& operator <<(std::ostream & out, const colour & c)
{
  switch (c)
  {
	case red:
	  return out << "red";
	case green:
	  return out << "green";
	case blue:
	  return out << "blue";
  }
  return out;
}

int main()
{	
	
	colour favourite;
	favourite = green;

	std::cout << favourite << std::endl;

	return 0;
}

gerard4143 code is very smart, maybe advanced.
enum is a constant name, with an integer value, so if you like to print the name of it self, you have to make a function, or higher level Operator.

if I do it with a function I will keep your code, and do next

#include <iostream>
#include <sstream>
#include <fstream>
#include "conio.h"
using namespace std;

string getPrintStr(int colorEnum)
{
switch (colorEnum)
  {
	case red:
	  return "red";
	case green:
	  return "green";
	case blue:
	  return "blue";
  }
return "unknown color";
}

int main()
{	
	enum colour {red, green, blue};
	colour favourite;
	favourite = green;

	cout << getPrintStr(favourite);

	_getch();
}
string getPrintStr(int colorEnum)
{
switch (colorEnum)
  {
	case red:
	  return "red";
	case green:
	  return "green";
	case blue:
	  return "blue";
  }
return "unknown color";
}

Your function should really be.

string getPrintStr(const colour & colorEnum)
{
switch (colorEnum)
  {
	case red:
	  return "red";
	case green:
	  return "green";
	case blue:
	  return "blue";
  }
return "unknown color";
}

thanks for the feedback

I dont think it fail if they both run, but I dont get why you passing the parameter by reference, and const
it also can be like the next without any problem,
enums are constant integers so you are very flexable to sent,
either enum colour or int,

string getPrintStr(enum colour colorEnum)

Your function should really be.

string getPrintStr(const colour & colorEnum)
{
switch (colorEnum)
  {
	case red:
	  return "red";
	case green:
	  return "green";
	case blue:
	  return "blue";
  }
return "unknown color";
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.