Caesar Cipher Gaming Project in C++

Explanation

  1. Include Libraries:
    • #include <iostream>: For input and output operations.
    • #include <string>: For using std::string.
  2. Encrypt Function:
    • string encrypt(string plaintext, int shift): Encrypts the plaintext using the Caesar cipher.
      • plaintext: The input string to be encrypted.
      • shift: The number of positions each letter in the plaintext is shifted.
      • Iterates over each character in plaintext:
        • Checks if the character is a letter (isalpha(c)).
        • Determines if it is uppercase or lowercase to set the base ('A' or 'a').
        • Applies the shift using modular arithmetic to ensure the result wraps around the alphabet.
        • Appends the encrypted character to ciphertext.
        • Non-alphabetic characters are added to ciphertext unchanged.
  3. Decrypt Function:
    • string decrypt(string ciphertext, int shift): Decrypts the ciphertext by using the inverse shift.
      • Calls the encrypt function with 26 - shift, as decryption in Caesar cipher is essentially shifting backwards by the same amount.
  4. Main Function (main):
    • Prompts the user to enter text and shift value.
    • Validates that the shift value is between 1 and 25.
    • Encrypts the input text using the encrypt function and prints the result.
    • Decrypts the encrypted text using the decrypt function and prints the result.

Notes:

  • Shift Value: The Caesar cipher typically uses a shift between 1 and 25 to avoid trivial cases where the shift is 0 or 26, which would not change the text.
  • Modular Arithmetic: Ensures that the shift wraps around the alphabet correctly.
  • Non-Alphabetic Characters: Are not altered by the cipher and are included as-is in the output.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top