One of the simplest examples of an encryption technology is the Caesar cipher, w
ID: 3546443 • Letter: O
Question
One of the simplest examples of an encryption technology is the Caesar cipher, which was used by Julius Caesar to communicate with his army. Caesar is considered to be one of the first persons to have ever employed encryption for the sake of securing messages. Caesar decided that shifting each letter in the message would be his standard algorithm, and so he informed all of his generals of his decision, and was then able to send them secured messages. Using the Caesar Shift (3 to the right), the message,
"Return to Rome" would be encrypted as, "Uhwxuq wr Urph".
Note that only letters are encoded. Punctuation, spaces, newlines, and so forth are not encoded. Lower case letters are encoded into lower case letters, and upper case letters are encoded into upper case letters. Also, note that the encoding system
Explanation / Answer
//You can find the same code with indentation here: http://snipt.org/Bahhg4/Slate
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
char type;
char infile[30];
char outfile[30];
int num=0;
cout << "Welcome to the Caesar cipher program." << endl;
cout << "Would you like to encrypt or decrypt a file (e/d)?" << endl;
cin >> type;
cout << type;
cout << " What is the shift value that you would like to use?:" <<endl;
cin >> num;
cout << num;
if(!(type=='e' || type=='d'))
exit(1);
if(type=='e')
cout << " Please tell the name of the file to encrypt:" << endl;
else
{
cout << " Please tell the name of the file to decrypt:" << endl;
num=-num;
}
cin >> infile;
cout << infile;
if(type=='e')
cout << " Please tell the name of the cipher file to write" << endl;
else
cout << " Please tell the name of the plain text file to write" << endl;
cin >> outfile;
cout << outfile;
vector<string> indata;
vector<string> outdata;
string string;
ifstream f;
int ascii;
f.open(infile);
if(f.is_open())
{
while(!f.eof())
{
getline(f,string);
//cout << indata;
indata.push_back(string);
}
}
else
cout<< "Sorry, can't open the input and/or output files. Exiting" << endl;
f.close();
int diff=0;
cout << endl;
for(int i=0;i<indata.size();i++)
{
std::string newstring;
for(int j=0;j<indata[i].size();j++)
{
ascii=(int)indata[i][j];
if(ascii>=65 && ascii<=90)
{
ascii=ascii+num;
if(ascii>90)
{
diff=ascii-90;
ascii=64+diff;
}
else if(ascii<65)
{
diff=65-ascii;
ascii=91-diff;
}
}
else if(ascii>=97 && ascii<=122)
{
ascii=ascii+num;
if(ascii>122)
{
diff=ascii-122;
ascii=96+diff;
}
else if(ascii<97)
{
diff=97-ascii;
ascii=123-diff;
}
}
//cout << (char)ascii;
newstring.push_back((char)ascii);
}
outdata.push_back(newstring);
}
ofstream of;
of.open(outfile);
for(int i=0;i<outdata.size();i++)
{
cout << outdata[i];
of << outdata[i];
}
of.close();
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.