• Welcome to Overclockers Forums! Join us to reply in threads, receive reduced ads, and to customize your site experience!

Adding numarical values to letters in C++...help please

Overclockers is supported by our readers. When you click a link to make a purchase, we may earn a commission. Learn More.

timmyqwest

Disabled
Joined
Nov 10, 2002
Location
illinois
I'm only 17 and i bought "C++ for dummies" about 3 months ago. As of right now this is purely a hobbie and i rarely sit down now adays and come up with stuff...but a math class a few months ago gave me a nifty idea. I'm going to write a program that codes/decodes messeges using matracies(SP?).

What i cant figure out how to do is to add a value to letters. I want A to be worth 1, and B to be 2 and C to be 3 and so on...

What would it look like?
 
Well, the ascii chars for the alphabet already have numerical values. Capital A = 97 and lowercase a = 65, if I recall correctly. The numbers increment from there. You could dump the values if you wanted with a simple loop:
Code:
char c;
for (c = 'a'; c <= 'z'; c++)
   printf("%c is %d\n", c, c);

So if you want A to correspond to a 1, you can just subtract from its ascii value. A more elegant method might be to use an enum or something, though.
 
If they already have values then i may be able to get it to work like that....

But when someone enters a string

"my name is bob"

does each letter have it's own value or is it differnt then?
 
Depends on how you handle the string. If you are using the string type in C++ then you'd have to work something out on your own. If you were using cstrings, then its just an array of characters.
 
You could create a paired list and give each letter a value. Then grab each character and look up it's value in the table. Using STL this would be a sinch.
 
Back