-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcaesar.cpp
More file actions
79 lines (66 loc) · 1.87 KB
/
Copy pathcaesar.cpp
File metadata and controls
79 lines (66 loc) · 1.87 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
75
76
77
78
79
/*
Caesar Chiper
J. P. Denata
*/
#include <iostream>
#include <string>
using namespace std;
// Function to encrypt the text
string encrypt(string text, int shift) {
string result = "";
// Loop through each character in the text
for (int i = 0; i < text.length(); i++) {
char ch = text[i];
// Encrypt uppercase letters (A-Z)
if (isupper(ch)) {
result += char(int(ch + shift - 65) % 26 + 65);
}
// Encrypt lowercase letters (a-z)
else if (islower(ch)) {
result += char(int(ch + shift - 97) % 26 + 97);
}
// If the character is not a letter, add it without encryption
else {
result += ch;
}
}
return result;
}
// Function to decrypt the text
string decrypt(string text, int shift) {
string result = "";
// Loop through each character in the text
for (int i = 0; i < text.length(); i++) {
char ch = text[i];
// Decrypt uppercase letters (A-Z)
if (isupper(ch)) {
result += char(int(ch - shift - 65 + 26) % 26 + 65);
}
// Decrypt lowercase letters (a-z)
else if (islower(ch)) {
result += char(int(ch - shift - 97 + 26) % 26 + 97);
}
// If the character is not a letter, add it without decryption
else {
result += ch;
}
}
return result;
}
int main() {
string text;
int shift;
// Input the text to be encrypted
cout << "Enter the text: ";
getline(cin, text);
// Input the desired shift
cout << "Enter the shift: ";
cin >> shift;
// Encrypt the text
string encrypted = encrypt(text, shift);
cout << "Encrypted text: " << encrypted << endl;
// Decrypt the text back
string decrypted = decrypt(encrypted, shift);
cout << "Decrypted text: " << decrypted << endl;
return 0;
}