用for循环写古典密码(向后移五位),读取用户输入的消息,然后使用encrypt
函数对消息进行加密,ncrypt
函数通过遍历消息中的每个字符,并将其向后移动五位来实现加密。(如果字符超过了字母表的范围,它会从字母表的另一端开始计算)
代码:
#include <stdio.h>
void encrypt(char *message, int shift) {
char c;
for(int i = 0; message[i] != '\0'; ++i) {
c = message[i];
if(c >= 'a' && c <= 'z'){
c = c + shift;
if(c > 'z'){
c = c - 'z' + 'a' - 1;
}
message[i] = c;
}
else if(c >= 'A' && c <= 'Z'){
c = c + shift;
if(c > 'Z'){
c = c - 'Z' + 'A' - 1;
}
message[i] = c;
}
}
}
int main() {
char message[100];
printf("请输入一条消息: ");
fgets(message, sizeof(message), stdin);
encrypt(message, 5);
printf("加密后的消息: %s", message);
return 0;
}
运行实例:
注意!!这个程序只对字母进行加密,对于非字母字符,它不会进行任何操作。