0

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;
        }
    }
}
Artjom B.
  • 58,311
  • 24
  • 111
  • 196
  • 1
    Possible duplicate of [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – 4386427 Aug 16 '17 at 09:29
  • Insert the line `if (in_stream.eof()) break;` just after `in_stream.get(letter);` – 4386427 Aug 16 '17 at 09:53
  • You know that the else is only being applied for the last condition? This should be fine for your code, but makes it harder to understand. – Lefsler Aug 16 '17 at 10:05
  • @4386427 thank you, inserting break; in conjunction with the answers below has solved my problem! – Brandon Holz Aug 16 '17 at 10:23

2 Answers2

-1

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.

Danyal Imran
  • 1,862
  • 7
  • 17
-1

I can suggest this piece of code

while(!in_stream.eof()) {
       if ((letter>='A' && letter<='Y')|| (letter>='a' && letter<='y'))
            letter = (letter+1);
       else if(letter== 'Z' || letter== 'z')
            letter =(letter-25);
    out_stream << letter;
}
Shiva
  • 17
  • 3