用c语言实现一下凯撒密码
时间: 2023-04-09 11:01:28 浏览: 104
我可以回答这个问题。凯撒密码是一种简单的加密方法,可以通过将明文中的每个字母向后移动固定数量的位置来加密。以下是用 C 语言实现凯撒密码的示例代码:
```c
#include <stdio.h>
#include <string.h>
void encrypt(char *plaintext, int shift);
int main()
{
char plaintext[100];
int shift;
printf("请输入明文:");
fgets(plaintext, sizeof(plaintext), stdin);
plaintext[strcspn(plaintext, "\n")] = '\0'; // 去掉输入字符串的换行符
printf("请输入移位数:");
scanf("%d", &shift);
encrypt(plaintext, shift);
printf("加密后的密文为:%s\n", plaintext);
return 0;
}
void encrypt(char *plaintext, int shift)
{
int i;
char c;
for (i = 0; plaintext[i] != '\0'; i++) {
c = plaintext[i];
if (c >= 'a' && c <= 'z') {
c = 'a' + (c - 'a' + shift) % 26;
} else if (c >= 'A' && c <= 'Z') {
c = 'A' + (c - 'A' + shift) % 26;
}
plaintext[i] = c;
}
}
```
这个程序可以接受用户输入明文和移位数,然后使用 `encrypt` 函数对明文进行加密,最后输出加密后的密文。