I am struggling with this assignment! In addition to posting code, if any explan
ID: 3558387 • Letter: I
Question
I am struggling with this assignment! In addition to posting code, if any explanation is given for syntax that would be appreciated, I would like to learn.
Background:
One of the simplest examples of an encryption technology is the Caesar cipher, which is said to have been 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
#include <iostream>
#include <string>
#include <math.h>
#include <fstream>
using namespace std;
char caesar( char c ,int sh)
{
if( isalpha(c) )
{
//c = toupper(c);
if(isupper(c))
c = (((c-65)-sh+26) % 26) + 65;
else
c = (((c-97)-sh+26) % 26)+97 ;
}
//if c isn't alpha, just send it back.
return c;
}
void characterCount(ifstream &myfile,int count[])
{
string line;
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
for(int i=0;i<line.length();i++)
{
count[toupper(line[i])-65]++;
}
}
}
else
cout << "Unable to open file";
}
void calshift(int &shift,int arr[])
{
int mx=arr[0],ind=0;
for(int i=0;i<26;i++)
{
if(arr[i]>mx)
{
mx=arr[i];
ind=i;
}
}
shift=ind-'e'+97;
}
void writeOutput(ifstream &myfile_r, ofstream &my_opfile, int shift)
{
string line;
string output="";
if(myfile_r.is_open())
{
while ( getline (myfile_r,line) )
{
// output="";
for(int i=0;i<line.length();i++)
{
output += caesar(line[i],shift);
}
output+=" ";
//cout<<output<<endl;
}
my_opfile<<output;
my_opfile<<" ";
myfile_r.close();
}
else
cout << "Unable to open file";
}
int main()
{
string inf,of,line,output;
int count[26]={0};
cout<<"enter the input and output file name"<<endl;
cin>>inf>>of;
ifstream myfile (inf.c_str());
characterCount(myfile,count);
ifstream myfile_r (inf.c_str());
ofstream my_opfile (of.c_str());
int shift=0;
calshift(shift,count);
writeOutput(myfile_r,my_opfile,shift);
system("pause");
} //end main
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.