用C++写一个位移密码
时间: 2023-12-27 21:47:53 浏览: 40
好的,以下是一个简单的C语言实现位移密码的代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 加密函数,str为要加密的字符串,n为位移数
void encrypt(char *str, int n) {
int len = strlen(str);
for (int i = 0; i < len; i++) {
if (isalpha(str[i])) {
str[i] = (str[i] - 'a' + n) % 26 + 'a';
}
}
}
// 解密函数,str为要解密的字符串,n为位移数
void decrypt(char *str, int n) {
int len = strlen(str);
for (int i = 0; i < len; i++) {
if (isalpha(str[i])) {
str[i] = (str[i] - 'a' - n + 26) % 26 + 'a';
}
}
}
int main() {
char str[100];
int n;
printf("请输入要加密的字符串:");
scanf("%s", str);
printf("请输入位移数:");
scanf("%d", &n);
encrypt(str, n);
printf("加密后的字符串:%s\n", str);
decrypt(str, n);
printf("解密后的字符串:%s\n", str);
return 0;
}
```
这个程序使用了两个函数encrypt和decrypt来分别进行加密和解密操作。其中,isalpha函数用于判断一个字符是否为字母,%运算符用于保证加密和解密操作都能够正确处理字母的循环移位。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)