Rize S. answered 03/23/23
Senior IT Certified Trainer, IT Developer & DBA Administrator
There were some minor issues in the code. I have fixed those and provided the updated code below:
#include <iostream>
#include <vector>
#include <set>
#include <string>
using namespace std;
class Substitution {
int key;
string input;
bool encipher;
public:
//constructor
Substitution(string msg, bool enc) : input(msg), encipher(enc) {}
//the function for encryption/decryption (Substitution algorithm)
string substitution();
};
class Cipher {
public:
virtual string encode(string) = 0;
virtual string decode(string) = 0;
};
///////////////////////////////////////////////////////////////////////
//the function for encryption/decryption (Substitution algorithm)
string Substitution::substitution() {
do {
cout << "Enter key in 1..25>> ";
cin >> key;
if (key > 25 || key < 1) {
cout << "KEY ERROR\n";
}
} while (key > 25 || key < 1);
string output = "";
for (int i = 0; i < input.size(); ++i) {
if (isalpha(input[i])) { //if letter
//offset='A' for upper letter, offset='a' for lower letter
char offset = isupper(input[i]) ? 'A' : 'a';
//find shift for current letter for encryption (key) or for decryption (26 - key)
int shift = encipher ? key : 26 - key;
//convert letter (shift letter)
char ch = (char)(((input[i] - offset + shift) % 26) + offset);
output += ch;
} else {
//non letter
output += input[i];
}
}
return output;
}
//the function for encryption/decryption (Caesar algorithm)
class CaesarCipher : public Cipher {
public:
//constructor
CaesarCipher(int shift) : shift(shift) {}
//the function for encryption
string encode(string input) {
string output = "";
for (int i = 0; i < input.length(); i++) {
if (isupper(input[i])) {
output += (char)((((int)input[i] + shift - 65) % 26) + 65);
} else if (islower(input[i])) {
output += (char)((((int)input[i] + shift - 97) % 26) + 97);
} else {
output += input[i];
}
}
return output;
}
//the function for decryption
string decode(string input) {
string output = "";
for (int i = 0; i < input.length(); i++) {
if (isupper(input[i])) {
output += (char)((((int)input[i] + (26 - shift) - 65) % 26) + 65);
} else if (islower(input[i])) {
output += (char)((((int)input[i] + (26 - shift) - 97) % 26) + 97);
} else {
output += input[i];
}
}
return output;
}
//function to change shift value for encryption/decryption
void setShift(const int& shift) {
this->shift = shift;
}
private:
int shift;
};
int main() {
/*
Encrypt a string entered by the user
Choose between two different encryption methods
Decrypt a string entered by the user
Choose between two different decryptions methods
Decrypt without knowing the encryption method (provide all possible outputs)
*/