与硬编码输入相比,使用fgets从用户处获取密钥时无法打印密钥流

问题描述 投票:0回答:1

我正在尝试使用fgets,而不是使用采用纯文本和键输入并返回键流和加密文本的程序对数组进行硬编码。使用fgets扫描用户的密钥会以某种方式更改输出,以不打印密钥流,而仅打印密钥本身。我唯一更改的是,不是使用数组对密钥字符串进行硬编码,而是让用户使用fgets输入密钥。

硬编码(摘要):

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

int main(void)
{
   char msg[] = "THECRAZYPROGRAMMER";
   char key[] = "HELLO";
   int msgLen = strlen(msg), keyLen = strlen(key), i, j;
   char newKey[msgLen], encryptedMsg[msgLen], decryptedMsg[msgLen];

   //generating new key
   for(i = 0, j = 0; i < msgLen; ++i, ++j){
      if(j == keyLen)
         j = 0;

    newKey[i] = key[j];
   }

   newKey[i] = '\0';
   printf("Original Message: %s", msg);
   printf("\nKey: %s", key);
   printf("\nNew Generated Key: %s", newKey);
}

fgets(摘要):

#include <stdio.h>
#include <string.h>
int main(void)
{
   char msg[512];
   char key[512];
   int msgLen = strlen(msg), keyLen = strlen(key), i, j;
   char newKey[msgLen], encryptedMsg[msgLen], decryptedMsg[msgLen];

   fgets(msg, 512, stdin);
   fgets(key, 512, stdin);

   //generating new key
   for(i = 0, j = 0; i < msgLen; ++i, ++j){
      if(j == keyLen)
         j = 0;

    newKey[i] = key[j];
   }

   newKey[i] = '\0';
   printf("Original Message: %s", msg);
   printf("\nKey: %s", key);
   printf("\nNew Generated Key: %s", newKey);
}
c encryption fgets vigenere
1个回答
0
投票

[检查下面的代码,对您的fgets代码进行一些编辑。

#include <stdio.h>
#include <string.h>
int main(void)
{
   char msg[512];
   char key[512];

   fgets(msg, 512, stdin);
   fgets(key, 512, stdin);

  int msgLen = strlen(msg), keyLen = strlen(key), i, j;
   char newKey[msgLen], encryptedMsg[msgLen], decryptedMsg[msgLen];

   //generating new key
   for(i = 0, j = 0; i < msgLen; ++i, ++j){
      if(j == keyLen - 1)
         j = 0;

    newKey[i] = key[j];
   }

   newKey[i] = '\0';
   printf("Original Message: %s", msg);
   printf("\nKey: %s", key);
   printf("\nNew Generated Key: %s", newKey);
}

我改变了两件事。首先,在调用msgLen之后,将代码移至keyLenfgets的位置,这样就不会占用strlen的未初始化内存。其次,我纠正了在if (j == keylen - 1)行中出现的一个一字不漏的错误,以便给定fgets的换行符不包含在您的输出中。

© www.soinside.com 2019 - 2024. All rights reserved.