I'm trying to create a caesar cipher in C++, and it keeps infinitely looping. Specifically, when inputting a non-numerical value for the key or for encrypting/decrypting, it loops the reset
function infinitely, and accepts an input when the user never gave one. Any ideas as to why this happens?
#include <iostream>
#include <cstring>
using namespace std;
bool x = false;
//Checks if the user wants to continue or not.
bool reset(bool x){
char cont;
while(cont != 'n' && cont != 'y'){
cout << "Would you like to continue? y/n \n";
cin >> cont;
if(cont == 'n'){
x = true;
}
if(cont != 'n' && cont != 'y'){
cout << "Invalid answer. \n";
}
}
return x;
}
//Encoding the text/shifting it up.
string encode(char message[], int key){
int chAscii;
for(int i = 0; message[i] != '\0'; i++){
chAscii = message[i];
chAscii = abs(chAscii);
//Encoding for lowercase letters.
if(chAscii >= 'a' && chAscii <= 'z'){
chAscii = chAscii + key;
chAscii = abs(chAscii);
//If the ASCII value of the character in question
//is greater than z, loop back around to a.
if(chAscii > 122){
chAscii = chAscii - int('z') + int('a') - 1;
}
message[i] = chAscii;
//Encoding for capital letters.
}else if (chAscii >= 'A' && chAscii <= 'Z'){
chAscii = chAscii + key;
//If the ASCII value of the character in question
//is greater than Z, loop back around to A.
if(chAscii > 'Z'){
chAscii = chAscii -'Z' + 'A' - 1;
}
message[i] = chAscii;
}
}
return message;
}
//Decoding the text/shifting it down.
string decode(char message[], int key){
int chAscii;
for(int i = 0;message[i] != '\0'; i++){
chAscii = message[i];
//Encoding for lowercase letters.
if(chAscii >= 'a' && chAscii <= 'z'){
chAscii = chAscii - key;
//If the ASCII value of the character in question
//is less than than z, loop back around to a.
if(chAscii < 97){
chAscii = chAscii + 'z' - 'a' + 1;
}
message[i] = chAscii;
//Encoding for capital letters.
}else if (chAscii >= 'A' && chAscii <= 'Z'){
chAscii = chAscii - key;
//If the ASCII value of the character in question
//is less than than Z, loop back around to A.
if(chAscii < 'A'){
chAscii = chAscii + 'Z' - 'A' + 1;
}
message[i] = chAscii;
}
}
}
int main() {
while(x == false){
//Initializing variables.
int choice;
char message[1000];
int key;
//Takes user input for what to encode/decode and by how much.
cout << "Enter text to be coded, ended by '~': ";
cin.getline(message, 1000, '~');
cout << "Enter amount to shift: ";
cin >> key;
cout << "Enter your choice:\n1 for Encryption, 2 for Decryption\n";
cin >> choice;
//Checks to see if we are encoding or decoding the text
if(choice == 1){
cout << encode(message, key);
}else if(choice == 2){
cout << decode(message, key);
}else{
cout << "Invalid choice.";
}
x=reset(x);
}
}