In: Computer Science
Task CPP
Some information on the Internet may be encrypted with a simple algorithm known as rot13, which rotates each character by 13 positions in the alphabet. A rot13 cryptogram is a message or word in which each letter is replaced with another letter.
For example, the string
the bird was named squawk
might be scrambled to form
cin vrjs otz ethns zxqtop
Details and Requirements
The test driver file lab3.cpp contains an incomplete implementation of the cipher as defined as the class Rot13.
To allow user input a string, you need to override the stream extraction operator >> for the Rot13 class. The class contains the string field text that must be filled with the input text.
Instructions
lab3.cpp
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class Rot13 {
friend ostream& operator<<(ostream&, const
Rot13&);
friend istream& operator>>(istream&, Rot13&);
string text;
public:
Rot13();
bool valid();
void encrypt();
};
bool Rot13::valid() {
}
void Rot13::encrypt() {
}
ostream& operator<<(ostream& out, const Rot13&
c) {
}
istream& operator>>(istream& in, Rot13& c)
{
}
/*
Please enter the text: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Invalid input!
Please enter the text: slkgjskjg akjf Adkfjd fsdfj
Invalid input!
Please enter the text: abcdefghijkl mnopqrst uvwxyz
Encoded text: "nopqrstuvwxy zabcdefg hijklm"
*/
int main() {
Rot13 cipher;
cout << "Please enter the text: ";
cin >> cipher;
if (!cipher.valid()) {
cout << "Invalid input!" << endl;
return 1;
}
cipher.encrypt();
cout << "Encoded text: " << cipher << endl;
return 0;
}
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class Rot13 {
friend ostream& operator<<(ostream&, const Rot13&);
friend istream& operator>>(istream&, Rot13&);
string text;
public:
Rot13();
bool valid();
void encrypt();
};
Rot13::Rot13(){
}
bool Rot13::valid() {
for(int i=0; i<text.length();i++){
char c = text[i];
if(('a' >c || 'z'<c) && c!=' ' ) return false;
}
return true;
}
void Rot13::encrypt() {
string result ="";
for(int i=0;i<text.length();i++){
char c = text[i];
if(c!=' ')
result += char(int(c+13-97)%26 +97);
else
result +=c;
}
text = result;
}
ostream& operator<<(ostream& out, const Rot13& c) {
out<<c.text;
}
istream& operator>>(istream& in, Rot13& c) {
getline(in,c.text);
}
/*
Please enter the text: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Invalid input!
Please enter the text: slkgjskjg akjf Adkfjd fsdfj
Invalid input!
Please enter the text: abcdefghijkl mnopqrst uvwxyz
Encoded text: "nopqrstuvwxy zabcdefg hijklm"
*/
int main() {
Rot13 cipher;
cout << "Please enter the text: ";
cin >> cipher;
if (!cipher.valid()) {
cout << "Invalid input!" << endl;
return 1;
}
cipher.encrypt();
cout << "Encoded text: " << cipher << endl;
return 0;
}