Search code examples
c++caesar-cipher

Caesar cipher encoding in C++: chars won't loop back to 'a' or 'A'


I'm working on coding a ceasar cipher that reads plaintext from a .txt, encrypts the plaintext and writes to a second .txt, then reads the second .txt and decrypts it to a third .txt. Everything is working except the encryption of characters near the end of the alphabet. When a character reaches 'z' or 'Z' it should loop back to 'a' or 'A'. Below is a snippet of code from my encoding function, this is the only bit that's causing issues.

if (isalpha(inputString[i])) {         //use isalpha() to ignore other characters
    for (int k = 0; k < key; k++) {     //key is calculated in another function, 6 in this case
        if (inputString[i] == 'z')      //these statements don't seem to work
            encryptedString[i] = 'a';
        else if (inputString[i] == 'Z')
            encryptedString[i] = 'A';
        else                            //this part works correctly
            encryptedString[i] ++;
    }               
}

Input:

THE quick brown fox

Jumped over the----

House or moon or some-thing.

Expected output:

ZNK waoiq hxuct lud

Pasvkj ubkx znk----

Nuayk ux suut ux yusk-znotm.

Actual Output:

THE q{ick bro}n fo~

J{mped o|er the----

Ho{se or moon or some-thing.

Key: 6


Solution

  • You are modifying encryptedString and then basing your "loop-over" decision on inputString.

    I suspect that you want to firstly initialize encryptedString from inputString, and then work only on encryptedString. It looks, to me, like you should do it like this:

    encryptedString[i] = inputString[i]; // initialize encryptedString
    if (isalpha(inputString[i]))
    {
        for (int k = 0; k < key; k++)
        {
            if (encryptedString[i] == 'z') // read from encryptedString instead of inputString
                encryptedString[i] = 'a';
            else if (encryptedString[i] == 'Z') // read from encryptedString instead of inputString
                encryptedString[i] = 'A';
            else
                encryptedString[i] ++;
        }               
    }