samedi 12 septembre 2020

Encrypt/Decrypt a C++ Array

I am trying to encrypt/decrypt a message that is input by the user (which can only include char or int) and then encrypt/decrypt that message based off the alphabet_digits array. For example, if the user inputs "abcd", then the output should be the index of each letter + 2. Code is below, but I can't figure out how to add 2 to each index value:

#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
#include <cstring>
#include <cstdlib>

using namespace std;

void choices();
char get_selection();

void p_selection();
void c_selection();
void unknown_selection();
void q_selection();

char alphabet_digits [] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n',
                            'o','p','q','r','s','t','u','v','w','x','y','z','0','1',
                            '2','3','4','5','6','7','8','9'};

int main(int argc, char* argv[]){

    char selection {};

    do{
        choices();
        selection = get_selection();
        switch(selection){
            case 'p':
                p_selection();
                break;
            case 'C':
                c_selection();
                break;
            case 'Q':
            case 'q':
                q_selection();
                break;
            default:
                unknown_selection();
        }
    } while(selection != 'p' || selection != 'C');

    cout << endl;
    return 0;
}

void choices(){
    /*
    This function tells the user which choices to enter into the prompt
    */
    cout<< "\nEnter p - ENCRYPT a set of characters" << endl;
    cout<< "Enter C - DECRYPT a set of characters" << endl;
    cout<< "Enter Q - Quit the program" << endl;

    cout<< "\nEnter your selection: ";
}

char get_selection(){
    char selection{};
    cin >> selection;
    return selection;
}

/*
SELECTION OPTIONS
*/
void p_selection(){
    string encrypted_message {};
    int k_value {};
    
    cout << "Enter message to encrypt: ";
    cin >> encrypted_message;
    cout << "Enter an integer for the k value: ";
    cin >> k_value;
    cout << "Encrypting message -p " << encrypted_message << " -k " << k_value << " -E" << endl;

    for(int i = 0; i < sizeof(alphabet_digits); i++){
        encrypted_message = encrypted_message + alphabet_digits[i + k_value];
    }
    cout << encrypted_message << endl;

}

void c_selection(){
    string decrypted_message {};
    int k_value {};
    
    cout << "Enter message to decrypt: ";
    cin >> decrypted_message;
    cout << "Enter an integer for the k value: ";
    cin >> k_value;
    cout << "Decrypting message -C " << decrypted_message << " -k " << k_value << " -D" << endl;

}

void q_selection(){
    cout << "Goodbye!" << endl;
    exit (EXIT_FAILURE);
}

void unknown_selection(){
    cout << "Unknown selection, please try again." << endl;
}

Thanks!

Aucun commentaire:

Enregistrer un commentaire