I wrote the following code for Ceaser cypher in C++. I am using a while loop hereenter code here
because when a user encrypts/decrypts a message there should be a loop for trying it again. But when I run the code, for the first iteration it is working perfectly fine, but when it runs for the second time it does not take the input string.
Here is my code
#include <conio.h>
#include <stdio.h>
#include <iostream>
using namespace std;
int main() {
char x = 'y';
int k, option;
string msg;
string encrypt;
string decrypt;
while (x != 'n') // run until user selects n
{
cout << "Please enter your message: ";
getline(cin, msg); // gets input message
cout << "\nEnter number for the key between 1-25: ";
cin >> k;
while (k < 1 || k > 25) {
cout << "\nPlease select valid key between 1 and 25 ";
cin >> k;
}
cout << "\nSelect option: "
<< "\n1 for Encrypt "
<< "\n2 for Decrypt "
<< "\n";
cin >> option;
while (option != 1 && option != 2) {
cout << "\nSorry wrong option. Please select again\n ";
cin >> option;
}
switch (option) {
case 1: // for encryption
for (int i = 0; i < msg.length(); i++) {
if (isalpha(msg[i])) {
if (islower(msg[i])) {
encrypt[i] = (((msg[i] - 97) + k) % 26) + 97;
cout << encrypt[i];
}
}
if (isupper(msg[i])) {
encrypt[i] = (((msg[i] - 65) + k) % 26) + 65;
cout << encrypt[i];
}
}
break;
case 2: // for decryption
for (int i = 0; i < msg.length(); i++) {
if (islower(msg[i])) {
decrypt[i] = ((((msg[i] - 97) - k) + 26) % 26) + 97;
cout << decrypt[i];
}
if (isupper(msg[i])) {
decrypt[i] = ((((msg[i] - 97) - k) + 26) % 26) + 97;
cout << decrypt[i];
}
}
break;
}
cout << "\nDo you want to try again?(Y/N) "; // asking user if he wants to
// encrypt or decrypt again
cin >> x;
}
}