Brandon Holz Brandon Holz -3 years ago 95
C++ Question

Encrypting a text file by incrementing chars

I need to encrypt a simple text file by incrementing each character by 1 i.e 'a' becomes 'b', 'b' becomes 'c' etc. with 'z' becoming 'a'.

I have done this as per the code below, and although majority of my output is correct, it seems to have trouble at the end of each file.

For example, when the input file contains 'a b c d' the output generated is 'b c d ef' as opposed to the answer which should be 'b c d e'. I cannot seem to figure this out.

This is my code for the encrypt function:

void encrypt(char* inFileName, char* outFileName) {
out_stream.open(outFileName);
in_stream.open(inFileName);
if(in_stream.fail()) {
cout << "Failed to open input file." << endl;
exit(1);
}
else {
while(!in_stream.eof()) {
in_stream.get(letter);

if (letter == 'z') {
letter = 'a';
}

if (letter == 'Z') {
letter = 'A';
}

if (letter == ' ') {
letter = letter;
}

else {
letter = letter + 1;
}

out_stream << letter;
}
}
}

Answer Source

Shift ciphers can be achieved using this way:

while(!in_stream.eof()) {
    if (letter>='a' && letter<='Z')
        letter = (letter+1)%'Z' + 'a';
    out_stream << letter;
}

Reduce redundancy from your code and make it as compact as possible, there are so many useless conditions in your code.

The main logic lies in ciphering characters from a...Z, you cannot predict other characters in text file such as \n \0 etc, so they shouldn't be dealt with at all.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download