enum type

Can some explain how to display an enum type variable, instead of the 0, 1, 2 value it represents?
Example:
1
2
3
4
5
6
7
8
9
10
11
// enumerated types
enum PhoneType {HOME, WORK, CELL};

// struct
struct RecordType
{
	string socialSecurityNumber;
	string lastName;
	string phoneNumber;
	PhoneType typePhone;
};

This is my enum type and struct i have defined.
I want to display the output so that the typePhone is displayed...i.e. HOME, WORK, or CELL...currently, i am saying
 
cout << ResidentRecords [i].typePhone << endl;

And it is displaying the ordinal value...the 0, 1, or 2..instead of HOME, WORK, or CELL

All help is greatly appreciated!!!
closed account (zb0S216C)
That's because enumerators don't have a string as their value, nor are they strings themselves. When the compiler sees an enumerator, it evaluates to its value, which is what you're seeing. There's no built-in way of converting an enumerator to a string, but you can use a switch:

1
2
3
4
5
6
7
8
9
10
11
12
switch( ResidentRecords[i].typePhone )
{
    case HOME:
        std::cout << "HOME";
        break;

    case WORK:
        std::cout << "WORK";
        break;

    /* ...and so on... */
}


Edit: You can use a macro:

1
2
#define TO_STRING( ID ) #ID
std::cout << TO_STRING( HOME );

However, it's a little extra to type.

Wazzak
Last edited on
Thanks for the help!! I understand now!
Note that you can't pass an actual variable to the stringize operator. It's a pre-processor command, so it takes what you pass it and returns it as a null terminated string:
1
2
3
4
enum foo{bar};
foo i[10];
i[0] = bar;
TO_STRING( i[0] ); //Will return the string "i[0]", not "bar". 
You can overload operator<< for PhoneType to make it work the way you want.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
std::ostream& operator<<(std::ostream& is, PhoneType typePhone)
{
	switch (typePhone)
	{
	case HOME:
		is << "HOME";
		break;
	case WORK:
		is << "WORK";
		break;
	case CELL:
		is << "CELL";
		break;
	}
	return is;
}
Topic archived. No new replies allowed.