gpt4 book ai didi

c - 维吉尼亚密码。代码输出

转载 作者:行者123 更新时间:2023-11-30 19:37:25 26 4
gpt4 key购买 nike

我一直在研究 cs50 pset2,我想在研究了几天后我已经掌握了 vigenere 密码。这段代码的目的是获取用户给出的字母参数(argv[]),并使用它作为 key 来通过字母索引中的数字来加密用户(字符串)给出的短语。例如,如果您给出参数“abc”和字符串“cat”,则输出应为“cbv”(a moving 0,b moving 1,c moving 2)该参数也应该环绕,以便如果字符串是更长的时间,参数将换行到其第一个字符并继续,直到字符串结束。

这是我的代码:

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


int main(int argc, string argv[])
{


if(argc != 2)
{
printf("Try again\n");
return 1;
}
string k = (argv[1]);

int klen = strlen(k);


for(int x = 0; x < klen; x++)
{
if(isalpha(k[x]))
{
if(isupper(k[x]))
{
k[x] = tolower(k[x]);
}

k[x] -= 'a';
}
else
{
printf("Try again\n");
return 1;
}
}

string code = GetString();

int clen = strlen(code);

for(int a = 0, b = 0; a < clen; a++)
{
if(isalpha(code[a]))
{
int key = k[b%klen];
if(isupper(code[a]))
{
printf("%c", (((code[a] - 'A') + key)%26) + 'A');
b++;
}
else
{
printf("%c", (((code[a] - 'a') + key)%26) + 'a');
b++;
}
}
else
{
printf("%c", code[a]);
}
}
printf("\n");
}

该代码似乎适用于 key 长度+1。例如,我输入参数“aaaa”

然后输入一串'bbbbb'并正确接收“bbbbb”。

但是,如果我输入相同的“aaaa”

然后输入比按键长的字符串+1'bbbbbbb'我收到“bbbbbNN”

我相信我的操作顺序有问题,但尝试移动括号却无济于事。我希望有人能指出正确的方向,解释为什么我的 key 没有正确包装。

最佳答案

使用这样的代码最大的风险是所有相似的、重复的子句。仅其中一个错误就很难追踪完成情况。在处理代码的同时对 key 进行任何处理都是低效的。

这是一个返工,在处理代码之前完全处理 key ,并尝试将处理简化为仅一种情况。看看它是否更适合您:

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

int main(int argc, string argv[])
{

if (argc != 2)
{
fprintf(stderr, "Try again\n");
return EXIT_FAILURE;
}

string key = strdup(argv[1]);

size_t key_length = strlen(key);

for (int x = 0; x < key_length; x++)
{
if (isalpha(key[x]))
{
if (isupper(key[x]))
{
key[x] = tolower(key[x]);
}

key[x] -= 'a';
}
else
{
fprintf(stderr, "Try again\n");
return EXIT_FAILURE;
}
}

string code = GetString();
int code_length = strlen(code);

for (int a = 0, b = 0; a < code_length; a++)
{
if (isalpha(code[a]))
{
int start = isupper(code[a]) ? 'A' : 'a';

printf("%c", (((code[a] - start) + key[b++ % key_length]) % 26) + start);
}
else
{
printf("%c", code[a]);
}
}

printf("\n");

free(key);

return EXIT_SUCCESS;
}

关于c - 维吉尼亚密码。代码输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39877973/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com