A shift cipher (a.k.a. Caesar’s cipher) is a simple substitution cipher in which each letter in the plaintext is replaced with another letter that is located a certain number, n, positions away in the alphabet. The value of n can be positive or negative. For positive values, replace letters with letters located n places on its right (i.e. ‘shifted’ by n positions to the right). For negative values, replace letters with letters located n places on its left. If it reaches the end/start of the alphabets, wrap around to the start/end. For example: If n = -3, each letter in the plaintext is replaced with a letter 3 positions before that letter in the alphabet list.
#include <iostream>
using namespace std;
string encrypt(string text, int s)
{
string result = "";
for (int i=0;i<text.length();i++)
{
if (isupper(text[i]))
result += char(int(text[i]+s-65)%26 +65);
else
result += char(int(text[i]+s-97)%26 +97);
}
return result;
}
int main()
{
string text="DEFENDATONECE";
int n = 4;
cout << "Text : " << text;
cout << "\nShift: " << n;
cout << "\nCipher: " << encrypt(text, n);
return 0;
}
Comments
Leave a comment