Caeser Cipher
Caeser Cipher
Assignment # 2
Caesar Cipher
1
Flow Chart:
Code:
#include <iostream>
#include <string>
2
// Function to encrypt text (including digits)
string encrypt(string text, int key) {
string result = "";
for (char c : text) {
if (isalpha(c)) { // Encrypt letters (A-Z, a-z)
char base = isupper(c) ? 'A' : 'a';
result += char((c - base + key) % 26 + base);
}
else if (isdigit(c)) { // Encrypt digits (0-9)
result += char((c - '0' + key) % 10 + '0');
}
else { // Keep special characters unchanged
result += c;
}
}
return result;
}
3
result += char((c - '0' - key + 10) % 10 + '0');
}
else { // Keep special characters unchanged
result += c;
}
}
return result;
}
int main() {
string text;
int key;
char choice;
cin.ignore();
cout << "\nEnter a string: ";
getline(cin, text);
4
cout << " [E] Encrypt Text \n";
cout << " [D] Decrypt Text \n";
cout << "Your choice: ";
cin >> choice;
choice = toupper(choice);
if (choice == 'E') {
cout << "Encrypted Text: " << encrypt(text, key) << "\n";
}
else if (choice == 'D') {
cout << "Decrypted Text: " << decrypt(text, key) << "\n";
}
else {
cout << "Invalid choice! Please enter E or D.\n";
}
return 0;
}
Output:
5
6