我正在为我的实验室工作表制作一个凯撒密码,并使它能够加密3次加密(凯撒的密码),这是练习的重点。但有一件事困扰着我。首先,如果我把它放在3之外,就会有一个尾随字符。例如,输入"malware",然后输入2表示键。这是我的密码:
#include<stdio.h>
#include<stdlib.h>
int main()
{
char text[100];
int key,i;
printf("Please enter a word/sentence (lowercaps) for encrypting :\n ");
fgets(text,100,stdin);
printf("Please enter the key that you desire : eg:14\n");
scanf("%d", &key);
for(i=0;i<strlen(text);i++)
{
if (key>=26)
{
key=key%26;
}
if (text[i]==' ')
{
continue;
}
if(text[i]+key>'z')
{
text[i]-=97;
text[i]+=26;
text[i]+=key;
text[i]%=26;
text[i]+=97;
}
else
{
text[i]=text[i]+key;
}
}
printf("this is your encrypted text : %s", text );
}我希望我遵循正确的缩进编码方法。所以有很多不喜欢的地方
发布于 2015-09-24 05:21:19
我将简化并更正这段代码
#include <stdio.h>
int main() {
char text[100];
int key, i;
printf("Enter a word / sentence (lowercaps) for encrypting : ");
fgets(text, 100, stdin);
printf("Enter the key that you desire (eg. 14) : ");
scanf("%d", &key);
key %= 26; // Pull this out of the loop and remove the unnecessary if
for (i = 0; text[i]; ++i) { // Correct the loop condition
if (text[i] == ' ') continue;
if (text[i] + key > 'z')
text[i] = (text[i] - 97 + 26) % 26 + 97; // Simplify
else
text[i] += key;
}
printf("Encrypted text : %s\n", text);
return 0;
}输入
Enter a word / sentence (lowercaps) for encrypting : malware
Enter the key that you desire (eg. 14) : 2输出
Encrypted text : ocnyctghttps://stackoverflow.com/questions/32753441
复制相似问题