/*
Name: Jake Reed
FileName: ReedJ caesar Cypher.cpp
Date: 3-25-2018
Description: This program allows user to encrypt and decrypt messages using the Casear Cypher*/
using namespace std;
void encode();
//Encodes a string message form the user and outputs the encoded message
void decode();
//Prompts the user for an encoded message and displays all possible (25)
//decoded plain text
int main(int argc, char** argv)
{
string strChoice;
do
{
cout << "+++++++++CAESAR CYPHER++++++++++\n\n"
<< "1. \tencode\n"
<< "2. \tdecode\n\n"
<< "Select a menu option: ";
It's essentially the same as your encode, but embedded in a loop where your random is the count variable... you don't need to reverse it. there's 26 letters. so if the encode is 10, and you encode it with 16 again, you'll get the original result....
Call srand() just once at the beginning of the program.
while(strChoice !="1" || strChoice !="2");
This is always true. The first part (strChoice != "1") is true for every string except "1". When the string is "1", the second part (strChoice != "2") is true because "1" != "2". You want && instead of ||.
Try creating a separate function that encodes a string:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
string
encodeString(const string &msg, int shift)
{
string result;
for (size_t n = 0; n < msg.length(); n++) {
// weed out spaces
char c;
if (isalpha(msg.at(n))) {
c = toupper(msg.at(n));
c = (((c - 65) + shift) % 26) + 65;
} else {
c = msg.at(n);
}
result += c;
}
return result;
}
Modify encode to call this:
1 2 3 4 5 6 7 8 9 10 11 12 13
void
encode()
{
//variables
string strMessage;
int randNum = rand() % 25 + 1;
// prompt user for the message
cout << "Type a message to encode: ";
getline(cin, strMessage);
cout << encodeString(strMessage, randNum) << endl << endl;
} //end encode()
Now the decode function is similar:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
void
decode()
{
//variables
string strMessage;
// prompt user for the message
cout << "Type a message to decode: ";
getline(cin, strMessage);
for (int i=1; i<26; ++i) {
cout << decodeString(strMessage, i) << '\n';
}
}
You just have to write decodeString(). Hint: it looks a whole lot like encodeString(). In fact, you can implement decodeString by calling encodeString()! If the string is encoded with a shift of 1, then it's decided with a shift of 25. Encode with shift 2 means decode with shift 24, etc.