繁体   English   中英

这是关于实现凯撒密码来加密用户给定的输入

[英]It's about implementing the Caesar-cipher code to encrypt the input given by the user

该代码接受要编码的输入(字符串)和来自用户的键,以便当将键添加到输入时,输入将增加给定键的数量。 对于前。 如果键为2,则输入A更改为C,b更改为d,依此类推。

我已经写了相同的代码,但无法获得输出。

int main()
{
  int x,i,y,c;
  char text[20];

  printf("enter the plaintext:");
  gets(text);
  printf("enter the key: ");
  scanf("%d",&x);
  for (y=0;y<strlen(text);y++)
  {
    if (text[i]>='a'&&text[i]<='z'&&text[i]>='A'&&text[i]<='Z' )
    {
      int c=(int)text[i]+x;
      printf("%c\n",text[i]);
    }
  }
}

我得到的结果是空白。 请帮助我。

您的提案中有很多问题,需要检查输入是否成功,您要在y而不是i上进行迭代,您需要计算新的char代码,但不打印它

这里是一个更正的建议:

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main()
{
  char text[100];

  printf("enter the plaintext:");

  if (fgets(text, sizeof(text), stdin) != NULL) {
    int key;

    printf("enter the key: ");
    if (scanf("%d", &key) == 1) {
      int i;

      for (i=0; text[i] != 0; ++i)
      {
       if (isalpha(text[i]))
         putchar(text[i] + key); /* may not be printable */
       else
         putchar(text[i]);
      }
    }
  }
  return 0;
}

编译与执行:

pi@raspberrypi:/tmp $ gcc -pedantic -Wextra c.c
pi@raspberrypi:/tmp $ ./a.out
enter the plaintext:the sentence to encode
enter the key: 3
wkh vhqwhqfh wr hqfrgh
pi@raspberrypi:/tmp $ ./a.out
enter the plaintext:Alea jacta est
enter the key: 2
Cngc lcevc guv

有趣的是,32不是编码大写字符的好键:

pi@raspberrypi:/tmp $ ./a.out
enter the plaintext:THE FIVE BOXING WIZARDS JUMP QUICKLY.
enter the key: 32
the five boxing wizards jump quickly.

您初始化了y变量而不是i变量
尝试这个 :

对于(i = 0; i <strlen(text); i ++){...}

注意 :
如果使用以下标志-Wall -Wextra -Werror编译代码,则可以帮助您更多地了解可能存在的错误,例如未使用的变量。
示例:gcc -Wall -Werror -Wextra youprogram.c -o输出

您不仅有其他错误,
因此,我建议您解决问题的方法:(所有输出字符均可打印)

#include <stdio.h>
#include <string.h>

int     main(void)
{
    char    text[250];
    size_t  i;
    int     key;

    printf("Enter the plaintext : ");
    if (fgets(text, sizeof(text), stdin) != NULL)
    {
            printf("Enter the key : ");
            scanf("%d", &key);
            for(i = 0; i < strlen(text); i++)
            {
                    if (text[i] >= 'a' && text[i] <= 'z')
                            putchar((((text[i] - 'a') + key) % 26) + 'a');
                    else if (text[i] >= 'A' && text[i] <= 'Z')
                            putchar((((text[i] - 'A') + key) % 26) + 'A');
                    else
                            putchar(text[i]);
            }
    }
    return (0);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM