I am making a cypher program for my C++ project. My approach is to declare and initialise two strings, the first one being alphabet and the other being key, as shown below.
string alphabet {"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"}; string key {"ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba"}; I want to pair all these 52 letters to one another in the cypher. That is, small a is replaced with capital Z, small b with Y and so on.
The user will be prompted to enter a string, which will be stored in input. My idea is to loop through the input string and match it with alphabet, and hence find out its pair in key string. This is easy, since the pairs will have the same index. However, how do I swap them? I can use a loop in swap(input[i], key[i]) but that will just make every string as ZYXW... I am not able to write the logic here... Below is my code till now in entirety.
#include <iostream> #include <string> using namespace std; int main() { string alphabet {"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"}; string key {"ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba"}; int choice {}; cout<<"Welcome to the Cypher Program"; cout<<"\nYou can encode and decode your messages to make sure they remain secret!"; cout<<"\nWould you like to encode(Press 1) or decode(Press 2) a message?"<<endl; cin>>choice; //Encoding if (choice == 1) { string input {}; cout<<"Enter a string to encrypt"<<endl; getline(cin.ignore(), input); //testString cout<<"Your encrypted message is: "<<endl; for(int i {0}; i<input.length(); i++){ swap(input[i], key[i]); } cout<<input; //ZYXWVUTSRQ } return 0; } What I really want to do is:
- Get input from user
- For each letter in input, find out its index in
alphabet - Using this index, swap the character with
key. - Display the new string back to user.
std::string’sfind()method will be usefulkeyshould be constant and it shall not be changed while encoding/decoding.