-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCaesar_Cipher.cpp
More file actions
74 lines (56 loc) · 1.76 KB
/
Caesar_Cipher.cpp
File metadata and controls
74 lines (56 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <bits/stdc++.h>
using namespace std;
// Encryption Function
void Encrypt(string inputText, int shift) {
// Iterate through each character
for(char &s: inputText) {
// Check for alphabet
if(isalpha(s)) {
// Check for uppercase or lowercase
if(s<'a') {
s+=shift; // Shift ascii value right
if(s>'Z') s-=26; // If shift exceeds z, cycle start from a
} else {
s+=shift; // Same procedure as above
if(s>'z') s-=26;
}
}
}
cout << "The encoded message is " << inputText << "\n";
}
//Decryption Function
void Decrypt(string inputText, int shift) {
// Iterate through each character
for(char &s: inputText) {
// Check for alphabet
if(isalpha(s)) {
// Check for uppercase or lowercase
if(s<'a') {
s-=shift; // Shift ascii value left
if(s<'A') s+=26; // If shift preceeds a, cycle back from z
} else {
s-=shift; // Same procedure as above
if(s<'a') s+=26;
}
}
}
cout << "The decoded message is " << inputText << "\n";
}
int main() {
string codeType, inputText;
int shift;
cout << "Type 'encode' to encrypt or 'decode' to decrypt: ";
cin >> codeType;
// Invalid case
if(codeType != "encode" && codeType != "decode") {
cout << "Invalid input\n";
return 0;
}
cout << "Type the message: ";
cin >> inputText;
cout << "Enter the number of shifts: ";
cin >> shift;
if(codeType == "encode") Encrypt(inputText,shift);
else Decrypt(inputText,shift);
return 0;
}