In: Computer Science
This is C++. It's based on structured data, chapter 11 of Starting out with C++. Please use basic operations. Please read the requirements carefully and make sure it's executable. The first 2 answers that I received are nowhere close. Thank you.
Secret Codes!
Create a program that will accept a message from the user and
either
encrypt ordecrypt it with the following algorithms:
To encrypt:
get the character you wish to encrypt
find the index of that character in the alphabet array
add the shift offset to the index
add the increment to the index
"wrap around" the new index so the result is between 0 and 29
find the character at the new index
To decrypt:
get the character you wish to decrypt
find the index of that character in the alphabet array
subtract the shift offset from the index
subtract the increment from the index
"wrap around" the new index so the result is between 0 and 29
find the character at the new index
repeat steps 1-6 for every shift offset
The alphabet is
<space>,a-z(lowercase),<period>,<question
mark>,
and <comma> in that order.
The increment should be +3 per letter position.
Here is a sample message. Who said it?
f..yqjrnvrpuabefw.j,ddxgcndpxmsdehsomjkcydfygtd.rrp?dgstmvxmf.wo?jxgrneslzifrgzyqv.v
#include <iostream>
using namespace std;
char c[]= {' ', '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', '.',
'?'};
int inc = 3;
string encrypt(string text, int s)
{
string result = "";
// traverse text
for (int i=0;i<text.length();i++)
{
if (islower(text[i]))
result += c[((text[i] - 'a' + 1) + s + inc)%29];
else if (text[i] == ' ')
{
result += c[(0 + s + inc)%29];
}
else if (text[i] == '.')
{
result += c[(27 + s + inc)%29];
}
else if (text[i] == '?')
{
result += c[(28 + s + inc)%29];
}
else
{
result += text[i];
}
}
// Return the resulting string
return result;
}
int wrapIndex(int i, int i_max) {
return ((i % i_max) + i_max) % i_max;
}
string decryptHelper(string text, int s)
{
string result = "";
// traverse text
for (int i=0;i<text.length();i++)
{
if (islower(text[i]))
result += c[wrapIndex((text[i] - 'a' + 1) - s - inc, 29)];
else if (text[i] == ' ')
{
result += c[wrapIndex(0 - s - inc, 29)];
}
else if (text[i] == '.')
{
result += c[wrapIndex(27 - s - inc, 29)];
}
else if (text[i] == '?')
{
result += c[wrapIndex(28 - s - inc, 29)];
}
else
{
result += text[i];
}
}
// Return the resulting string
return result;
}
void decrypt(string text)
{
for (int i = 0; i < 28; i++)
{
cout << "Shift s: " << i << " decrypted string: "
<< decryptHelper(text, i) << endl;
}
}
// Driver program to test the above function
int main()
{
string text="attackatonce";
int s = 4;
cout << "Text : " << text;
cout << "\nShift: " << s;
string cipher = encrypt(text, s);
cout << "\nCipher: " << cipher;
cout << "Possible decryption: " << endl;
decrypt(cipher);
return 0;
}
Output: