C语言 : there is a trailing character after the last character of my output

标签 c encryption caesar-cipher

我正在为我的实验表制作凯撒密码,并使其能够加密 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() 加密非字母,包括 '\n' 这导致 OP 的“在我输出的最后一个字符之后的尾随字符”。

相反:

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/

相关文章:

python - 如何去掉 python 中凯撒类次程序的空格?

C语言凯撒密码——加密与解密

c - 生成浮点随机值(也为负)

java - RSA 解密 - BadPaddingException : Data must start with zero

ruby - 在 Ruby 中创建凯撒密码,出现错误

c++ - 在 C++ 生成器中使用 hashlib++ 时出错?

java - 仅提供 key 的 Java 中的 Openssl -aes-256-cbc

c - 如何在函数中分配数组,然后重新分配它

c - c 中的动态类型

c++ - 无法使用 gcc 构建 sigqueue 示例,但 g++ 可以吗?