C语言用for循环实现凯撒密码加密
时间: 2024-11-27 07:24:27 浏览: 32
凯撒密码是一种简单的替换式加密算法,通过将明文中的每个字符向后移动固定位数来进行加密。下面是一个使用 C 语言 for 循环实现凯撒密码加密的例子,假设偏移量是固定的 3(即 A 变成 D,B 变成 E,依此类推):
```c
#include <stdio.h>
#include <string.h>
void caesar_cipher_encrypt(char* plaintext, int shift) {
int len = strlen(plaintext);
char encrypted[len];
for (int i = 0; i < len; i++) {
// 对字母进行处理
if ('A' <= plaintext[i] && plaintext[i] <= 'Z') { // 大写字母
encrypted[i] = ((plaintext[i] - 'A' + shift) % 26) + 'A';
} else if ('a' <= plaintext[i] && plaintext[i] <= 'z') { // 小写字母
encrypted[i] = ((plaintext[i] - 'a' + shift) % 26) + 'a';
} else { // 非字母字符不变
encrypted[i] = plaintext[i];
}
}
printf("Encrypted text: %s\n", encrypted);
}
int main() {
char input[100];
printf("Enter a plain text message: ");
fgets(input, sizeof(input), stdin); // 注意fgets避免结束符
// 删除输入字符串结尾的换行符
input[strlen(input) - 1] = '\0';
caesar_cipher_encrypt(input, 3); // 使用shift值3作为示例
return 0;
}
```
在这个例子中,用户会被提示输入明文,然后程序会将其加密并输出到屏幕上。如果你想改变加密强度,只需更改 `caesar_cipher_encrypt` 函数内的 `shift` 参数即可。
阅读全文
相关推荐


















