凯撒密码算法c++实现
时间: 2023-11-25 14:50:23 浏览: 213
以下是凯撒密码算法的C++实现:
```c++
#include <iostream>
#include <string>
using namespace std;
string encrypt(string plaintext, int k) {
string ciphertext = "";
for (int i = 0; i < plaintext.length(); i++) {
if (isalpha(plaintext[i])) {
char c = plaintext[i];
if (isupper(c)) {
c = (c + k - 'A') % 26 + 'A';
} else {
c = (c + k - 'a') % 26 + 'a';
}
ciphertext += c;
} else {
ciphertext += plaintext[i];
}
}
return ciphertext;
}
int main() {
string plaintext;
int k;
cout << "请输入明文:";
getline(cin, plaintext);
cout << "请输入密钥:";
cin >> k;
string ciphertext = encrypt(plaintext, k);
cout << "加密后的密文为:" << ciphertext << endl;
return 0;
}
```
阅读全文