C++ Program to Implement Caesar Cipher
Posted by Superadmin on August 08 2022 06:15:32

C++ Program to Implement Caesar Cipher

 

 

This is a C++ Program to implement Caesar Cipher Encryption algorithm. This is the simplest of all, where every character of the message is replaced by its next 3rd character.

 

Here is source code of the C++ Program to Implement Caesar Cypher. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. char caesar(char);
  5. int main()
  6. {
  7.     string input;
  8.     do
  9.     {
  10.         cout << "Enter cipertext and press enter to continue." << endl;
  11.         cout << "Enter blank line to quit." << endl;
  12.         getline(cin, input);
  13.         string output = "";
  14.         for (int x = 0; x < input.length(); x++)
  15.         {
  16.             output += caesar(input[x]);
  17.         }
  18.         cout << output << endl;
  19.     }
  20.     while (!input.length() == 0);
  21. } //end main
  22.  
  23. char caesar(char c)
  24. {
  25.     if (isalpha(c))
  26.     {
  27.         c = toupper(c); //use upper to keep from having to use two seperate for A..Z a..z
  28.         c = (((c - 65) + 13) % 26) + 65;
  29.     }
  30.     //if c isn't alpha, just send it back.
  31.     return c;
  32. }

Output:

$ g++ CaesarCipher.cpp
$ a.out
 
Enter cipertext and press enter to continue.
Enter blank line to quit.
Sanfoundry
FNASBHAQEL
Enter cipertext and press enter to continue.
Enter blank line to quit.
 
 
------------------
(program exited with code: 0)
Press return to continue