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 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
|
#include<iostream>
#include<string>
using namespace std;
string Encrypt(string&, int &);// 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
//system("Pause");
return 0;
}
string Encrypt(string& Source, int& c)
{
char fUpperCase[26] = { '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[26] = { '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
int z;//z holds the value (int) of the length of the user input ( including spaces)
z = (int)Source.length(); /*give the variable z the value of the user input length and length is normally an unsigned long integer hence
we have to typecast it*/
/*counter that makes it keep looping until it "encrypts" all of the user input (that's why it keeps looping while its less than z)*/
for (int i = 0; i < z; i++)
{
for (int j = 0; j < 26; j++)
{
if (Source[i] == fLowerCase[j] || Source[i] == fUpperCase[j])
{
//text[i] = fLowerCase[j];
if (c > 0)
{
//another counter that loops forwards key times by incrementing method
for (int counter = 0; counter < c; counter++)
{
/*it checks if the letter text[x] is 'z' and if it is 'z' it will make it 'a'*/
/*if (Source[i] == 'z')
{
Source[i] = 'a';
}
else if (Source[i] == 'Z')
{
Source[i] = 'A';
}*/
//else
//{
Source[i]++;
//}
}
}
else if (c < 0)
{
//another counter that loops backwards key times by decrementing method
for (int counter = 0; counter < abs(c); counter++)
{
/*it checks if the letter text[x] is 'a' and if it is 'a' it will make it 'z'*/
if (Source[i] == 'a')
{
Source[i] = 'z';
}
else if (Source[i] == 'A')
{
Source[i] = 'Z';
}
else
{
Source[i]--;
}
}
}
else
{
Source[i];//No alphabet shifts
}
}
}
}
return Source;
}
|