In: Computer Science
Write a C++ program performing the rot13 cipher, 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 rot13 cipher is tested a second time, the original plantext should be restored: 'P' becomes 'C', 'N' becomes 'A'. The 13 letters go in a rotation so if we have 'Z', 13 letters ahead of it is 'M'. So using c++ perform the rot13 cipher.
#include <iostream> #include <string> using namespace std; string encrypt_or_decrypt(string str) { string ret = ""; char ch; for(int i = 0; i < str.length(); ++i) { ch = str[i]; if(ch >= 'A' && ch <= 'Z') { ch = ((ch-'A'+13)%26) + 'A'; } if(ch >= 'a' && ch <= 'z') { ch = ((ch-'a'+13)%26) + 'a'; } ret += ch; } return ret; } int main() { string str; cout << "Enter a sentence: "; getline(cin, str); string cipher = encrypt_or_decrypt(str); cout << "converted to rot13: " << cipher << endl; cout << "decrypted to get original message: " << encrypt_or_decrypt(cipher) << endl; return 0; }