Alright, after much frustration I have a code that does what I want. The problem is that I'm not comfortable with functions and as a result I've got one big ugly main function.
The biggest obstacle is that I'm still a bit confused about what parameters I would pass through to my functions as well as how to have my function access data from my ifstream variable.
As I see it, there is, at minimum, two functions that I could make using the while loops in my main, but maybe three. My main function does the following:
1) Ask user for file name and open file. If file !open then we output an appropriate response
2) (using a while(!eof) loop) A) Read character by character to track occurrences of a letter. B) Create a "shift" value that will shift each letter by an amount that makes our highest occurring letter == 'e'.
3) (using a while(!eof) loop) Read character by character & manipulate each letter using the shift value while preserving whitespace/punctuation and print new letters to the screen.
I'll post the beast below:
HTML Code:
// This is the Caesar Cipher program
// This program will read in data and decypher it
// Chase Banta
// 24 may 2013
// Sources:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
// Declaring variables for use throughout program
ifstream fromFile;
string fileName;
char ch;
int letterCount[26] = {0};
int index;
int mostCommon = 0;
int shift = 0;
int tracker = 0;
string wholeDoc;
// Prompting user to enter file name and opening file
cout << "Please enter the file name you wish to decypher : ";
cin >> fileName;
cout << endl << endl;
fromFile.open(fileName.c_str());
// If a file is not found in the location suggested by the user
// an appropriate error message outputs and the program quits.
if (!fromFile.is_open()) {
cout << "An error has occured. File name not found." << endl;
getchar();
getchar();
return 0;
}
while (!fromFile.eof()){
fromFile >> ch;
ch = toupper(ch);
index = ch -'A';
if(index < 26 && index >= 0) {
letterCount[index]++;
}
}
for(index = 0; index < 26; index++) {
if(letterCount[index] > tracker) {
tracker = letterCount[index];
mostCommon = index;
}
}
shift = (('A'+ mostCommon)-'E') ;
fromFile.clear();
fromFile.seekg(0);
while (!fromFile.eof()){
fromFile >> ch;
if(islower(ch)){
ch -=shift;
if(ch < 'a'){
ch+=26;
}
}
if(isupper(ch)){
ch -=shift;
if(ch < 'A'){
ch +=26;
}
}
cout << static_cast<char>(ch);
}
getchar();
getchar();
return 0;
}
The only way that this program doesn't do what I would like is that when it prints out, it doesn't "text wrap". Is there something I can use from the iomanip library for that?