Help with a Rot13 Program Bug

My program seems to be adding an extra character at the end the output file. Is there any way to stop this from happening?

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

using namespace std;

int main() {
	char c;
	ifstream fin;
	ofstream fout;

	fin.open("secretMessage.txt");
	fout.open("decodedMessage.txt");

	while (!fin.eof()) {
		fin.get(c);
		if ((c >= 'A'&&c <= 'M') || (c >= 'a'&&c <= 'm')) {
			c = (c + 13); //converts text through rot 13
			fout << c;
		}
		else if ((c >= 'N'&&c <= 'Z') || (c >= 'n'&&c <= 'z')) {
			c = (c - 13); //converts text through rot 13
			fout << c;
		}
		else {
			c = c;
			fout << c;
		}
	}
	fin.close();
	fout.close();
	return 0;
}
Last edited on
Never loop on eof. It is almost never right and leads to all sort of errors. In your case: reading one character more than needed. Loop on input operation.
1
2
3
	while (!fin.eof()) {
		fin.get(c);
	while (fin.get(c)) {
Last edited on
I can't seem to get that to work either. If I loop in on input op it will output even worse gibberish than the original message.
closed account (48T7M4Gy)
Your first step is to make the recommended changes.

The next step is to comment out all your code in the loop and just display character c. That will tell you whether the read file process is going ok.

Then you proceed with your code slowly but surely from there.

It's next to impossible to debug reams of code ie test as you go, not in big slabs.

BTW Hint: Rot13 is a modular arithmetic exercise and you need to limit the range of the ascii code range accordingly because that's more than likely what the gibberish is all about.

cheers :)
Might that be because you forgot to remove the fin.get(c) line inside the body of the loop?
Topic archived. No new replies allowed.