DEV Community

Discussion on: Daily Challenge #42 - Caesar Cipher

Collapse
 
lordapple profile image
LordApple • Edited

C++

#include <iostream>

int main(){
    unsigned key = 1;
    std::string toEncrypt = "defend the east wall of the castle";

    if(key < 1 || key > 26){
        std::cout << "Key must be in range of 1-26" << std::endl;
        return 0;
    }

    for(char& c : toEncrypt){
        if(c < 'A' || c > 'z'){
            continue;
        }else if(c + key > 'z'){
            c = 'a' + (c + key) % 122 - 1;
            continue;
        }else if(c + key > 'Z' && c < 'a'){
            c = 'A' + (c + key) % 90 - 1;
            continue;
        }

        c += key;
    }
    std::cout << toEncrypt;
    return 0;
}