In: Computer Science
Write a C++ program which performs a rot 13 substitution. Must be in C++. Thank you.
CodeToCopy:
rot13.cpp
#include <iostream> /* for cin, cout */
using namespace std;
/* string variable holds lower case letters */
string lower_case_letters = "abcdefghijklmnopqrstuvwxyz";
/* string variable holds upper case letters */
string upper_case_letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
/* function encodes and decodes the input string using
* rot13 substitution cipher */
string rot13(string input) {
/* string variable to hold output */
string output;
/* holds the position of input character in alphabet */
int letter_pos;
/* loop to iterate over input string */
for (int i = 0; i < input.size(); ++i) {
/* finding the position of input character in lower_case_alphabet */
letter_pos = lower_case_letters.find(input[i]);
if (letter_pos < 0) {
/* finding the position of input character in upper_case_alphabet */
letter_pos = upper_case_letters.find(input[i]);
if (letter_pos < 0) {
/* its not a character in alphabet, so not doing anything */
output.append(1, input[i]);
continue;
}
/* getting the position of 13th character from current character */
letter_pos = (letter_pos + 13) % 26;
/* appending it to output */
output.append(1, upper_case_letters[letter_pos]);
}
else {
/* getting the position of 13th character from current character */
letter_pos = (letter_pos + 13) % 26;
/* appending it to output */
output.append(1, lower_case_letters[letter_pos]);
}
}
/* returning input */
return output;
}
/* driver code to test to above function */
int main() {
/* taking input from the user */
string input;
cout << "input: ";
cin >> input;
/* getting rot13 encoded text and printing */
string output = rot13(input);
cout << "encoded: " << output << endl;
/* getting rot13 decoded text and printing */
cout << "decoded: " << rot13(output) << endl;
return 0;
}
OutputScreenshot: