用C语言写代码 PTA例题7-12 凯撒加密(后偏移)
时间: 2025-02-16 16:15:46 浏览: 107
凯撒加密,也称为后移加密,是一种简单的替换式密码技术,其原理是将明文中的每个字符按照固定的位移量向字母表后方移动。以下是使用C语言编写的一个基本的凯撒加密程序,实现了对输入字符串进行后偏移加密:
```c
#include <stdio.h>
#include <ctype.h>
char caesar_encrypt(char c, int shift) {
if (isalpha(c)) { // 判断字符是否为字母
if (islower(c)) {
return ((c - 'a' + shift) % 26) + 'a';
} else {
return ((c - 'A' + shift) % 26) + 'A';
}
} else {
return c; // 非字母字符保持不变
}
}
void caesar_cipher_encrypt(const char *plaintext, int shift, char *ciphertext) {
int i;
for (i = 0; plaintext[i] != '\0'; ++i) {
ciphertext[i] = caesar_encrypt(plaintext[i], shift);
}
ciphertext[i] = '\0'; // 结束字符串并添加终止符
}
int main() {
char plaintext[100], ciphertext[100];
printf("请输入明文:\n");
fgets(plaintext, sizeof(plaintext), stdin); // 输入忽略空格
plaintext[strlen(plaintext) - 1] = '\0'; // 去除fgets的换行符
int shift;
printf("请输入偏移量(1-25):\n");
scanf("%d", &shift);
caesar_cipher_encrypt(plaintext, shift, ciphertext);
printf("加密后的密文:\n%s\n", ciphertext);
return 0;
}
```
在这个程序中,`caesar_encrypt`函数用于单个字符的加密,`caesar_cipher_encrypt`函数则遍历整个字符串并将每个字符加密。用户首先输入明文,然后选择一个1到25之间的偏移量,程序会计算并打印出相应的密文。
阅读全文
相关推荐










