1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
|
#include<iostream>
#include<string>
using std::cout;
using std::cin;
using std::endl;
using std::string;
string Encrypt(string Source, int c);// Function Prototype. This declares Encrypt to be a function that needs one variable
// as string and another as integer as arguments. Reference operator & in prototype
int main()
{
string text;//the string that holds the user input
int key;//key holds the number by which the user wants the alphabets to be shifted
cout << "Enter your phrase: " << endl;
getline(cin, text);//gets the user input ( including spaces and saves it to the variable text)
cout << "Please choose a number(key) for which you wants the alphabets to be shifted: " << endl;
/*Note: the key can either be positive (forward shifting), negative (backward shifting) or zero (no shifting)*/
cin >> key;//User input for number by which alphabets are going to be shifted
cout << "Encrypted Message: " << Encrypt(text, key) << endl; //Function call to display encrypted message
return 0;
}
string Encrypt(string Source, int c)
{
int i, j,letter;
char fUpperCase[27] = { ' ', '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' };//Initialization of class member
char fLowerCase[27] = { ' ', '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'};//Initialization of class member
string cipher = "";
int z = Source.length();
for (i = 0; i < z; i++)
{
for (j = 0; j < 27; j++)
{
if (Source[i] == fLowerCase[j])
{
letter = j + c;
if (letter > 27) // If found letter + key is greater than array size
letter -= 27; // Subtract 27
if (letter < 0) // If found letter - key is less than 0
letter += 27; // Add 27
cipher += fLowerCase[letter];
}
else if (Source[i] == fUpperCase[j])
{
letter = j + c;
if (letter > 27) // If found letter + key is greater than array size
letter -= 27; // Subtract 27
if (letter < 0) // If found letter - key is less than 0
letter += 27; // Add 27
cipher += fUpperCase[letter];
}
}
}
return cipher;
}
|