#include<iostream>
#include<fstream>
#include<string>
usingnamespace std;
void count (int letters[26]);
int findMax (int letters[26]);
void decrypt(int shift);
char fileName[151]; // allow for a very long file location
int main() {
int letters[26] = {0};
//function for determining most common letter
count (letters); //function
// crack the case
int shift = findMax(letters) - 4;
// decrypt rest of file
decrypt(shift);
// pause and exit
getchar();
return 0;
}
void count(int letters[26]) {
//declare variables
ifstream infile;
int index;
char ch;
cout << "Please enter the directory location of the file you wish to decrypt: " << endl;
cin >> fileName;
infile.open(fileName); // open the encrypted file
while(!infile.eof()) {
infile.get(ch);
ch = toupper(ch); // capitalilze letters to halve variance
index = static_cast<int>(ch) // change letters into numbers
- static_cast<int>('A');
if (0 <= index && index < 26)
++letters[index];
infile.close();
}
}
// function to determine most common letter in file
int findMax (int letters[26]) {
int maxIndex = 0;
for (int index = 0; index < 26; index++)
if (letters[maxIndex] < letters[index])
maxIndex = index;
return maxIndex;
}
void decrypt(int shift) {
ifstream infile;
char ch;
int change;
int shifted;
infile.open(fileName);
while(!infile.eof()) {
infile.get(ch);
if (ispunct(ch)) //print punctuation
cout << ch;
elseif (ch = ' ') //print whitespace
cout << " ";
elseif (ch) {
change = static_cast<int>(ch); //change letters to ints to perform shift
shifted = ch - shift;
if (shifted < 65)
shifted = shifted + 25; //add the alphabet back on to roll back if the ASCI value gets too low
if (ch < 97) { //capitalize
static_cast<char>(shifted);
shifted = toupper(shifted);
cout << shifted;
}
static_cast<char>(shifted);
cout << shifted;
}
}
}