In: Computer Science
Write a C++ program performing the rot13 cipher:
Basically the code should perform like this:
The user should be able to input any letter or words, or even sentences where once they have inputted the particular word, each letter goes 13 letters ahead, so an 'A' becomes an 'N', a 'C' becomes 'P', and so on. If the rot13 cipher is applied a second time, the original plantext is restored: 'N' becomes 'A', 'P' becomes 'C'. The 13 letters go in a rotation so if for example we have 'Z', 13 letters ahead of it is 'M'. So perform the rot13 cipher using C++.
#include <iostream>
using namespace std;
string rot13encrypt(string orig, int rshift){
string result = "";
rshift = rshift%26;
// traverse text
for (int i=0;i<orig.length();i++)
{
if(orig[i] ==' ' || isdigit(orig[i]) || !isalpha(orig[i]) )
result += orig[i];
else if (isupper(orig[i]))
result += char(int(orig[i]+rshift-65)%26 +65);
// Encrypt Lowercase letters
else
result += char(int(orig[i]+rshift-97)%26 +97);
}
// Return the resulting string
return result;
}
string rot13decrypt(string orig, int rshift){
string result = "";
rshift = rshift%26;
// traverse text
for (int i=0;i<orig.length();i++)
{
if(orig[i] ==' ' || isdigit(orig[i]) || !isalpha(orig[i]) )
result += orig[i];
else if (isupper(orig[i])) {
int v = orig[i]-rshift-65;
int k = (26 + (v%26)) % 26;
result += char(k +65);
}
// Encrypt Lowercase letters
else {
int v = orig[i]-rshift-97;
int k = (26 + (v%26)) % 26;
result += char(k +97);
}
}
// Return the resulting string
return result;
}
void display(string rot13){
cout<<"After rot13 "<<rot13<<endl;
}
int main()
{
string text;
int shift;
cout<<"Enter the text: ";
getline(cin,text);
cout<<"Original String: "<<text<<endl;
string str = rot13encrypt(text,13);
display("Encryption: "+ str);
string rot13 = rot13decrypt(str,13);
display("Decryption: "+ rot13);
}
=========================================
SEE OUTPUT
Thanks, PLEASE COMMENT if there is any concern.