Decryption Program Broken

I am terrible at this. Learning a lot though. Can anyone point out where I went wrong?

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<fstream>
#include<string>

using namespace 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;
		
		else if (ch = ' ')		//print whitespace
		cout << " ";
		
		else if (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;

		}
	}
}
At first glance, line 77 should be else if (ch == ' ').

I don't have the time to go through it all right now though, sorry.

It might be helpful if you tell us what exactly is going wrong (what should be happening vs what is happening with a certain input).
Last edited on
Topic archived. No new replies allowed.