What is meant is that you are "shifting" the
positions of symbols in the symbol lookup table.
For an alphabetic shift cipher (like Caesar's), your lookup table starts out looking like this:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
Shifting by 2 (for a Caesar cipher) does this:
CDEFGHIJKLMNOPQRSTUVWXYZAB
(You could also call this a "rotate", but terminology is what it is.)
The way to "shift" is through an addition with remainder.
C = (A + 2) % 26
There's a trick, though. The underlying value of
'A' is not zero, so you must also account for that:
(c + 'A') = ((p - 'A') + 2) % 26
So we can rearrange that equation a little and write it in code:
1 2
|
char p = //next plaintext character to encode
char c = ((p - 'A' + 2) % 26) + 'A';
|
You may want to add additional checks to make sure you are only converting 'A'..'Z' and 'a'..'z', or you may wish to widen your symbol table to include all printable characters (more than 26), or whatever.
One other hint: unless your assignment specifically says to play create a plaintext file, don't. Use your code editor to create a plaintext file to encode, then pass it to your program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
int main()
{
std::string infilename;
std::cout << "input file name? ";
getline( std::cin, infilename );
std::ifstream infile( infilename );
std::string outfilename;
std::cout << "output file name? ";
getline( std::cin, outfilename );
std::ofstream outfile( outfilename );
std::cout << "encrypt or decrypt? ";
char c;
std::cin >> c;
switch (std::toupper(c))
{
case 'E': ...
case 'D': ...
default: ...
}
}
|
Even better, use command-line arguments:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
int main( int argc, char** argv )
{
if (argc != 4)
{
std::cerr << "usage:\n "
<< argv[0] << " e|d INFILE OUTFILE\n";
return 1;
}
std::ifstream infile( argv[2] );
std::ofstream outfile( argv[3] );
switch (std::toupper( argv[1][0] ))
{
case 'E': ...
case 'D': ...
default: ...
}
}
|
C:\prog> copy con plain.txt
Hello world!
Time flies like an arrow,
Fruit flies like a banana.
^Z
1 file(s) copied.
C:\prog> a encrypt plain.txt cipher.txt
C:\prog> type cipher.txt
Jgnnq yqtnf!
Vkog hnkgu nkmg cp cttqy,
Htwkv hnkgu nkmg c dcpcpc.
C:\prog> a decrypt cipher.txt recovered.txt
C:\prog> type recovered.txt
Hello world!
Time flies like an arrow,
Fruit flies like a banana.
C:\prog> |
Hope this helps.