写一个caesar加密c++
时间: 2023-07-30 09:09:37 浏览: 50
好的,以下是一个简单的 Caesar 加密 C++ 程序:
```c++
#include <iostream>
#include <string>
using namespace std;
string encrypt(string plaintext, int key) {
string ciphertext = "";
for (int i = 0; i < plaintext.length(); i++) {
// 对每个字符进行加密
char c = plaintext[i];
if (isalpha(c)) {
c = toupper(c);
c = ((c - 65 + key) % 26) + 65;
}
ciphertext += c;
}
return ciphertext;
}
int main() {
string plaintext;
int key;
cout << "请输入明文:";
getline(cin, plaintext);
cout << "请输入密钥:";
cin >> key;
string ciphertext = encrypt(plaintext, key);
cout << "密文为:" << ciphertext << endl;
return 0;
}
```
这个程序中,`encrypt` 函数接受明文和密钥作为参数,返回加密后的密文。在 `encrypt` 函数中,我们使用一个 `for` 循环遍历明文中的每个字符,并对其进行加密。如果这个字符是一个字母,我们将它转换为大写,并使用 Caesar 加密算法对它进行加密。最后,我们将加密后的字符添加到密文字符串中,并返回它。
在 `main` 函数中,我们首先从用户那里获取明文和密钥。然后,我们调用 `encrypt` 函数进行加密,并输出加密后的密文。