Ceasar Cipher
Mar 11, 2012 at 3:59am UTC
I am having some serious trouble! I have written some code and had some help with it, but I can figure out how to, with the current code, to take in a large text file and run the decryption. Here is the code I have come up with. I feel like it's clunky and not particularly efficient. sorry! Please Help!
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
#include <iostream>
#include <string>
#include <cstring>
#include <fstream>
using namespace std;
void Caesar(string& phrase, int shift);
int find_the_e(string phrase);
int main(){
int shift = 0;
string inputFileName;
ifstream inputFile;
string reply;
char character;
string phrase = "I am having a hard time wiht the file I/O" ;
Caesar(phrase, shift);
cout << "Encrypted Phrase: " << phrase << endl << endl;
shift = find_the_e(phrase); //Find the most common letter
cout << endl << "Most common letter was - " << (char )(4-shift+97) << " - so shifting " << shift << endl << endl;
Caesar(phrase, shift);
cout << "Translated Phrase: " << phrase << endl << endl;
cin.sync();
cin.get();
return 0;
}
int find_the_e(string phrase){
int letters[26];
int highest = 0;
char a = 'a' ;
for (int i = 0; i < 26; ++i)
letters[i] = 0;
for (int i = 0; i < phrase.size(); ++i){
if (isalpha(phrase[i])){
letters[(int )tolower(phrase[i])-97]++;
}
}
for (int i = 0; i < 26; ++i, ++a){
if (letters[i] > letters[highest])
highest = i;
}
return 4-highest;
}
void Caesar(string& phrase, int shift){
if (shift > 0){
for (; shift > 0; --shift){
for (int i = 0; i < phrase.size(); ++i){
if (phrase[i] == 'z' ){
phrase[i] = 'a' ;
continue ;
}
else if (phrase[i] == 'Z' ){
phrase[i] = 'A' ;
continue ;
}
if (isalpha(phrase[i]))
phrase[i]++;
}
}
}
else if (shift < 0){
for (; shift < 0; ++shift){
for (int i = 0; i < phrase.size(); ++i){
if (phrase[i] == 'a' ){
phrase[i] = 'z' ;
continue ;
}
else if (phrase[i] == 'A' ){
phrase[i] = 'Z' ;
continue ;
}
if (isalpha(phrase[i]))
phrase[i]--;
}
}
}
else return ;
}
Topic archived. No new replies allowed.