凯撒加密c++23 abc4 yz
#include
string caesarCipher(string text, int shift) { string result = "";
// Loop through each character in the text
for (int i = 0; i < text.length(); i++) {
// Check if the character is a letter
if (isalpha(text[i])) {
// Shift the character by the shift amount
char shiftedChar = text[i] + shift;
// Check if the shifted character is out of range
if ((isupper(text[i]) && shiftedChar > 'Z') || (islower(text[i]) && shiftedChar > 'z')) {
shiftedChar -= 26; // Wrap around to the beginning of the alphabet
}
result += shiftedChar;
}
else {
result += text[i]; // Non-letter character, add it as is
}
}
return result;
}
int main() { int shift; string text;
// Get the shift amount from the user
cout << "Enter the shift amount: ";
cin >> shift;
// Get the text to encrypt from the user
cout << "Enter the text to encrypt: ";
cin.ignore(); // Ignore the newline character left by the previous input
getline(cin, text);
// Encrypt the text using the Caesar cipher
string encryptedText = caesarCipher(text, shift);
// Output the encrypted text
cout << "Encrypted text: " << encryptedText << endl;
return 0;
原文地址: https://www.cveoy.top/t/topic/fDj2 著作权归作者所有。请勿转载和采集!