我正在为我的实验表制作凯撒密码,并使其能够加密 3 代入(凯撒密码),这是练习的重点。但是有一件事困扰着我。首先,如果我输入 3 以外的字符,则有一个尾随字符。例如,输入“恶意软件”,然后输入 2 作为 key 。 这是我的代码:
#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 );
}
我希望我遵循了正确的编码缩进方法。也因此遭到了很多人的反对
最佳答案
代码是 1) 无法正确检测 char
何时为小写字母 2) 从 fgets() 加密非字母,包括
这导致 OP 的“在我输出的最后一个字符之后的尾随字符”。'\n'
相反:
if (text[i] >= 'a' && text[i]<= 'z') {
text[i] = (text[i] - 'a' + key)%26 + `a`;
}
else {
; // nothing
}
或者
if (islower((unsigned char) text[i]) {
text[i] = (text[i] - 'a' + key)%26 + `a`;
}
注意:以上依赖char
编码为ASCII .
不依赖于 ASCII 的解决方案。
static const char lowercase[] = "abcdefghijklmnopqrstuvwxyz";
char *p = strchr(lowercase, text[i]);
if (p) {
int offset = (p - lowercase + key)%26;
text[i] = lowercase[offset];
}
关于C语言 : there is a trailing character after the last character of my output,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32753441/