yet another question about enums....

Hello,

I want to make a c++ practice problem based on chess.
My trouble with enum, reduced to the essence is this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

enum letters { a, b,c,d,e };

int main ()
{
	letters a_letter;
	int i;
	for (i = 0; i< 5; i++)
	{
		a_letter = (letters)i;
		cout << a_letter;
	}

}


this outputs 12345
and I want it to output abcde

What am I doing wrong?
01234, you mean?

Anyway, 'a' in the enum is an identifier. 'a' you want to see is a character (or string). These to don't have much in common. You can't go from one to another.
A thing you could do is enum letters { a = 'a', b,c,d,e }; and cout << (char)a_letter;. This simply sets the value of identifier 'a' to the ascii code of character 'a'. This would not work for strings though.

Though you really shouldn't do this. Enums are a kind of integer constants used when their actual values are irrelevant (as long as they are different). Conversions form or to integers go against this logic. Use simple constants for that.
Thanks for the reply, hamsterman.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

enum letters { a='a', b='b',c='c',d='d',e='e' };

int main ()
{
	letters a_letter;
	int i;
	for (i = 0; i< 5; i++)
	{
		a_letter = (letters)i;
		cout << (char)a_letter;
	}

}


This doesn't work as expected, I get non-abcde ASCII characters.
I thought this could be a nice way to automatically fill out the pieces names (chars) in relation to their game value, but I was wrong.
Thank you very much for your help, I'll come back to this some rainy day.

Andrei
This works:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

enum letters {a,b,c,d,e};
char letterVals[5] = {'a','b','c','d','e'};

int main ()
{
	letters a_letter;
	int i;
	for (i = 0; i < 5; i++)
	{
		a_letter = (letters)i;
		cout << letterVals[a_letter];
	}
}
Oh, right. I didn't think about that.
If you had done
1
2
letters a_letter = a;
cout << (char) a_letter;
It would have worked, but now you assign 0, 1, etc. to a_letter, you get (char)0, (char)1, (char)etc. which are all not letters.
Hello,

Thank you all for your help!

A const char array is the best sollution for my program.
I guess I'm not that good programmer matherial. ;)


Topic archived. No new replies allowed.