1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
|
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
const int MAXSIZE = 26;
void characterCount (char ch, int list[]);
void calcShift (int& shift, int list[]);
void writeOutput (ifstream &input, ofstream &output, int shift);
int main ()
{
int list [MAXSIZE];
int asciiCode = 0;
int shift = 0;
string filename;
char ch;
ifstream infile;
ofstream outfile;
cout << "input the file name";
getline (cin, filename);
infile.open (filename.c_str());
if (!infile)
{
cout << " the file did not open or path could not be found";
system ("pause");
exit (1);
}
cout << "please enter the output file name";
getline (cin, filename);
outfile.open (filename.c_str());
while (infile)
{
infile.get (ch);
characterCount (ch, list);
}
calcShift (shift, list); // find the shift by factoring the most counted letter is e
writeOutput (infile, outfile, shift);
return 0;
}
void characterCount (char ch, int list [])
{
int index;
ch = toupper(ch);
index = static_cast<int>(ch) - static_cast<int> ('A');
if (0 <= index && index < 26)
list[index]++;
}
void calcShift (int& shift, int list[])
{
int maxIndex = 0;
int largest = 0;
for (int i = 1; i < MAXSIZE; i++)
{
if (list [maxIndex] < list [i])
maxIndex = i;
}
largest = list[maxIndex]; //When the maxIndex is found, then that has the largest number.
if (largest >= 65 && largest <= 90) //Calculate shift with <strong class="highlight">E</strong> (for upper-case letters)
shift = largest - 69;
if (largest >= 97 && largest <= 122) //For lower-case letters (<strong class="highlight">e</strong>)
shift = largest - 101;
}
void writeOutput(ifstream &infile, ofstream &outfile, int shift)
{
char ch;
int asciiCode = 0;
while (infile) { //Until it is the end of the file...
infile.get(ch); //Get the next character
if (ch >= 'A' && ch <= 'z') //If the character is in the alphabet...
{
asciiCode = static_cast<int>(ch); //Change it to the ASCII number
asciiCode += shift; //Do the shift
ch = static_cast<char>(asciiCode); //Change it to the shifted letter
}
outfile << ch; //Print to the outfile
}
|