Letter to number and number to letter

closed account (21vXjE8b)
Maybe this is a homework question, but I can't find a way of solving it...
In my code, you put a message to be codified (hello), put a key value (e.g. 3) and the result is KHOOR (3 letters forward).
The problem is that the code is long. I did 52 If statements! So I need to simplify it!
Each letter has a number, like A = 1, B = 2, ... , Z = 26. It adds to these numbers the value of the key value (if the result is more than 26, it subtracts 26). If the final result is 1, we have A; 2, we have B; ... ; 26, we have Z.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
for (i=0; i < msgToEncrypt.length(); i++) {
		
		if (msgToEncrypt[i] == 'A' || msgToEncrypt[i] == 'a') a = 1;
		if (msgToEncrypt[i] == 'B' || msgToEncrypt[i] == 'b') a = 2;
		if (msgToEncrypt[i] == 'C' || msgToEncrypt[i] == 'c') a = 3;
                ...
                if (msgToEncrypt[i] == 'Z' || msgToEncrypt[i] == 'z') a = 26;
		
		b = a + key_value;
		
		if (b > 26) b -= 26;
		
		if (b == 1) c = 'A';
		if (b == 2) c = 'B';
		if (b == 3) c = 'C';
                ...
                if (b == 26) c = 'Z';
		
		cout << c;
}


I wanna know if there's a command that change letter to number and number to letter, replacing the 52 If statements!
Last edited on
Realise that a char is just a small int, so you can do math with it:

1
2
char MyChar = 'A';
char EncyptedChar = MyChar +3;  // is character 'D', using ASCII 


Hope this helps !!
closed account (48T7M4Gy)
Might like to throw in modular arithmetic there too, in order to stay within the bounds of whatever alphanumeric system is chosen and therefore avoid non-printing characters especially.
closed account (48T7M4Gy)
.
Last edited on
closed account (21vXjE8b)
Thank you TheIdeasMan! That helped me a lot!
I noticed that kemort... But, how can I apply modular arithmetic in this case?

1
2
3
4
5
6
7
8
9
char c, i;
string msgToEncrypt;

for (i=0; i < msgToEncrypt.length(); i++) {
		
		c = msgToEncrypt[i] + key_value;
				 
		cout << c;
}


Last edited on
closed account (48T7M4Gy)
.
Last edited on
closed account (48T7M4Gy)
https://en.wikipedia.org/wiki/Caesar_cipher
closed account (21vXjE8b)
Got it!!! Thank you!
Topic archived. No new replies allowed.