Best way to create variables for the alphabet

I want to create a program that uses character variables for the whole alphabet, but is there any shorter way to do that than just listing them all out? This is what I have now:

char a;
char b;
char c;
char d;

and so on...

Is that the best way to do that?
char alphabet[ 26 ];

To populate it with the alpha bet:
1
2
3
4
5
6
7
char alphabet[ 26 ];

	for( int i = 0; i < 26; ++i )
		alphabet[ i ] = i + 97; //97 is the decimal for 'a' in ascii

	for( int i = 0; i < 26; ++i )
		std::cout << alphabet[ i ] << ' ';


ascii:
http://www.asciitable.com/
I suspect you don't need variables at all and can just use literals:

This is wrong:
1
2
3
4
char userinput = /* get from the user */

if(userinput == a)  // did the user press A?
 ...


This is right:

1
2
3
4
char userinput = /* get from the user */

if(userinput == 'a')  // did the user press A?
 ...


Note the 'a' in the 2nd example is inside single quotes. This makes it a literal (you're actually comparing to the letter 'a', not a variable that just happens to be named a).


If that's not what you need, and you actually do need a variable for each letter of the alphabet, you can use an array:

 
char alphabet[26];




EDIT:

@ Lynx:

alphabet[ i ] = i + 97; //97 is the decimal for 'a' in ascii

To make that less confusing and elimnate the need for the comment, you could just use the literal:

alphabet[ i ] = i + 'a';
Last edited on
Wow! Thanks for giving the right help to a n00b!
1
2
3
To make that less confusing and elimnate the need for the comment, you could just use the literal:

alphabet[ i ] = i + 'a';


I actually never knew that! ahaha. Think I did that once at uni a long time ago.
For reference, if you actually DO need to make a bunch of variables of the same type, you can use this syntax:
char a, b, c, d, e;

Be careful though! Pointers are different:
char* a, b;
Only a is a pointer, b is just a char. For clarity, put the * against the variable name and not the type name.
Topic archived. No new replies allowed.