// decode.cpp allows its users to decode a message stored in a file
// using the Caesar cipher.
//
// The encoded message is stored in a file.
//
// Begun by: Joel C. Adams, for Hands On C++.
// Completed by:
// Date:
//
// Specification:
// input(input file): an encoded sequence of characters.
// output(output file): the sequence of decoded input characters.
//*********************************************************************
#include <iostream> // stream I/O
#include <string> // string, isupper(), islower()
#include <cassert> // assert()
using namespace std;
char CaesarDecode(char ch, int key);
int main()
{
// 0. Display introductory message
cout << endl << "This program uses the Caesar cipher to decode the contents of a"
<< endl << "file and writes the decoded characters to another file." << endl;
// 1. Prompt for and read the name of the input file
cout << endl << "Enter the name of your input file: ";
string inFile;
cin >> inFile;
// 2. Open an ifstream named inStream for input to inFile
// 3. If inStream failed to open, display an error message and quit
assert( /* inStream opened succesfully */ );
// 4. Prompt for and read the name of the output file
cout << endl << "Enter the name of your output file: ";
string outFile;
cin >> outFile;
// 5. Open an ofstream named outStream for output to outFile
// 6. If outStream failed to open, display an error message and quit
assert( /* outStream opened successfully */);
char inChar, outChar;
// 7. Loop
for (;;)
{
// a. read a character from the input file via inStream into inChar
// b. if end-of-file was reached, terminate repetition
// c. decode the character using the Caesar cipher
outChar = CaesarDecode(inChar, 3);
// d. write the decoded character to the output file via outStream
}
// 8a. close the connection to the input file
// 8b. close the connection to the output file
// 9. display a 'successful completion' message
}
//*******************************************************************
// CaesarDecode implements the Caesar cipher encoding scheme. *
// *
// Receive: ch, a character, *
// key, an integer. *
// Return: The character that is key positions before ch, *
// with "wrap-around" to the end of the sequence. *
//*******************************************************************
#include <cstdlib> // exit()
#include <cctype> // isupper(), islower()
char CaesarDecode(char ch, int key)
{
const int FIRST_UPPER = int('A'),
FIRST_LOWER = int('a'),
NUM_CHARS = 26;
if (key <= 0 || key >= 26)
{
cerr << endl << "*** CaesarDecode: key must be between 1 and 25!" << endl;
exit(1);
}
if (isupper(ch))
return (ch - FIRST_UPPER + NUM_CHARS - key) % NUM_CHARS + FIRST_UPPER;
else if (islower(ch))
return (ch - FIRST_LOWER + NUM_CHARS - key) % NUM_CHARS + FIRST_LOWER;
else
return ch;
}