请用C++编程凯撒密码生成的过程
时间: 2024-05-04 15:18:37 浏览: 197
以下是使用C++编写凯撒密码生成的代码示例:
```cpp
#include <iostream>
#include <string>
using namespace std;
// 凯撒密码加密函数
string caesarCipher(string plaintext, int key) {
string ciphertext = "";
// 遍历明文中的每个字符
for (int i = 0; i < plaintext.length(); i++) {
// 获取当前字符的ASCII码
int ascii = (int)plaintext[i];
// 大写字母移位
if (ascii >= 65 && ascii <= 90) {
ascii = (ascii - 65 + key) % 26 + 65;
}
// 小写字母移位
else if (ascii >= 97 && ascii <= 122) {
ascii = (ascii - 97 + key) % 26 + 97;
}
// 将移位后的ASCII码转换为字符并添加到密文中
ciphertext += (char)ascii;
}
return ciphertext;
}
int main() {
// 明文和密钥
string plaintext = "Hello, world!";
int key = 3;
// 加密并输出密文
string ciphertext = caesarCipher(plaintext, key);
cout << "Plaintext: " << plaintext << endl;
cout << "Ciphertext: " << ciphertext << endl;
return 0;
}
```
代码中,`caesarCipher`函数接收明文和密钥作为参数,返回密文。函数内部遍历明文中的每个字符,根据字符的ASCII码进行移位操作,最后将移位后的字符拼接成密文。在`main`函数中,我们定义了一个明文和密钥,并使用`caesarCipher`函数进行加密,最后输出密文。
阅读全文
相关推荐


















