What's up with the mod 57? What does that number come from? I assume it's an attempt to deal with capital lettering?
whenever I input either character 'y' or 'z', the program adds 2 to the ascii assignment instead of the intended 1. I don't know why it occurs only with these characters but works fine for all the others. |
Let's try out the math.
65 == 'a'
120 == 'x' --> 120 - 65 + 1 = 56, 56 % 57 = 56, 56 + 65 = 121 == 'y'
but then...
121 == 'y' --> 121 - 65 + 1 = 57, 57 % 57 = 0, 0 + 65 = 0 == 'A'
The problem is that you incorrectly implementing the modular "wrap-around" logic.
Inputting 'Z' would not work correctly either. 57 isn't going to solve that.
Are you sure you have to make A -> B and a -> b? Usually these types of ciphers just stick with either all caps (or they represent lowercase as the cleartext, and ALL CAPS as the ciphertext). But it's not too big of a deal, you just have to change the offset if it's a capital letter.
Let's just focus on lowercase. That's working in modulo 26.
We want a -> b, but z -> a (wrap back around)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
#include <iostream>
#include <cctype> // islower
using namespace std;
int main() {
const int CRYPT_KEY = 1;
char char1;
cout << "Enter letter: ";
cin >> char1;
cout << char1 << endl;
int ascii = static_cast<int>(char1) + CRYPT_KEY;
ascii = ((ascii - 'a') % 26) + 'a';
char1 = static_cast<char>(ascii);
cout << "Encrypted letter: " << char1;
return 0;
}
|
but now we want to incorporate capital letters as well. Simply change the offset from 'a' to 'A'.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
#include <iostream>
#include <cctype>
using namespace std;
int main() {
const int CRYPT_KEY = 1;
char char1;
cout << "Enter letter: ";
cin >> char1;
cout << char1 << endl;
int ascii = static_cast<int>(char1) + CRYPT_KEY;
if (islower(char1))
ascii = ((ascii - 'a') % 26) + 'a';
else
ascii = ((ascii - 'A') % 26) + 'A';
char1 = static_cast<char>(ascii);
cout << "Encrypted letter: " << char1;
return 0;
}
|
I'm sure you could do something fancy to eliminate the if statement, but that should do just fine.