凯撒密码代码#include <stdio.h>
#include <string.h>
#include <ctype.h>
// 函数声明
void caesarEncrypt(char *plaintext, int shift);
void caesarDecrypt(char *ciphertext, int shift);
int main() {
char text[100];
int shift;
printf("请输入文本(最多100个字符):");
fgets(text, sizeof(text), stdin); // 读取包含空格的字符串
text[strcspn(text, "\n")] = '\0'; // 去掉换行符
printf("请输入偏移量(正数为加密,负数为解密):");
scanf("%d", &shift);
if (shift > 0) {
caesarEncrypt(text, shift);
printf("加密后的文本:%s\n", text);
} else if (shift < 0) {
caesarDecrypt(text, -shift);
printf("解密后的文本:%s\n", text);
} else {
printf("偏移量不能为0!\n");
}
return 0;
}
// 凯撒密码加密函数
void caesarEncrypt(char *plaintext, int shift) {
for (int i = 0; plaintext[i] != '\0'; i++) {
if (isalpha(plaintext[i])) { // 检查是否为字母
char base = islower(plaintext[i]) ? 'a' : 'A';
plaintext[i] = (plaintext[i] - base + shift) % 26 + base;
}
}
}
密钥:3
题目:Wdnh Olqh 9 wr Vkdqjkdl Vhfrqg Srobwhfkqlf Xqlyhuvlwb