gpt4 book ai didi

c - C 语言的维吉尼亚密码 : Space not being ignored

转载 作者:行者123 更新时间:2023-11-30 15:32:42 31 4
gpt4 key购买 nike

Vignere 密码的一般解释:

维涅尔密码是一种类似于凯撒密码的加密方法。该密码接受一个单词作为参数,并将该单词的字母解释如下:a 为 0,b 为 1,c 为 2,依此类推。

因此,如果您的输入 key 是“abc”并且您想要加密“hi hello”之类的内容,则输出将需要 h 保持不变,i 移动 1 位,h 移动 2 位,e 再次保持不变相同(因为它被移动了 0),l 移动了 1 位,另一个 l 移动了 2 位,依此类推。

基本思想是每个字母移动参数中对应的字母,并且忽略空格和其他标点符号。如果参数比消息短(在大多数情况下都是如此),则参数将简单地围绕消息循环。

<小时/>

我的问题:

唯一存在的问题是它似乎对句子的第一个单词做了正确的事情。它并没有忽略空格。

我已在下面粘贴了我的新代码。

例如,对于程序./vigenere bacon和消息上午十一点在公园见我,我期望Negh zf av huf pcfx bt gzrwep oz 作为输出。然而,我得到的是 Negh ne og tjs qaty bt svfvgb bm。或者例如,当我在 ABCD ABCD 上运行程序 ./vignere bc 时,我会期望 BDDF BDDF。相反,我得到的是 BDDF CCEE(当它应用类似于 bcbcbcbcb 的内容而不是 bcbc bcbc 时的输出。

虽然第一个单词正确更改,但它似乎正在加密整个句子,而它应该只加密字母表 - 我已使用 isalpha 命令指定了这一点。

这就是为什么看起来有点令人费解的原因。

代码:

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

int main(int argc, string argv[])

{
string word = argv[1];
int i = 0;
int j = 0;


if (argc != 2 || isalpha(word[j]) == false)
{
printf("Please enter a valid command line argument! \n");
return 1;
}

else if (isalpha(word[j]))
{
printf("Message: ");
string message = GetString();

for (int n = strlen(message); i < n; i++)
{
int plaintext = message[i];
int ciphertext = word[j];
int uppcb = (plaintext - 65 + ciphertext - 65);
int upcipher1 = (uppcb) % 26;
int uplc = (plaintext - 65 + ciphertext - 97);
int upcipher2 = (uplc) % 26;
int lopcb = (plaintext - 97 + ciphertext - 97);
int locipher1 = (lopcb) % 26;
int lolp = (plaintext - 97 + ciphertext - 65);
int locipher2 = (lolp) % 26;

if (isupper(word[j]) && isupper(message[i]))
{
j = (j+1)%strlen(word);
int upcode = (upcipher1 + 65);
printf("%c", upcode);
}

else if (isupper(message[i]) && islower(word[j]))
{
j = (j+1)%strlen(word);
int upcode1 = (upcipher2 + 65);
printf("%c", upcode1);
}

else if (islower(message[i]) && islower(word[j]))
{
j = (j+1)%strlen(word);
int locode = (locipher1 + 97);
printf("%c", locode);
}

else if (islower(message[i]) && isupper(word[j]))
{
j = (j+1)%strlen(word);
int locode1 = (locipher2 +97);
printf("%c", locode1);
}

else
{
printf("%c", message[i]);
}

}
printf("\n");
}


}

注意:这实际上是 C 而不是 C++,并且我正在使用的 CS50 库中提供了一些命令,例如 GetInt() 和 GetString()。

最佳答案

您需要变量 word 的另一个索引变量如jwordmessage是两个不同的变量,它们的长度可能不同。

所以代替 if (isupper(word[i]) && isupper(message[i]))你会得到类似 if (isupper(word[j]) && isupper(message[i])) 的东西其中索引变量j从零开始计数到 ​​strlen(word) - 1然后从零重新开始。

它适用于您的特殊情况的原因是 messageword长度相同,因此无需重新启动 word 的索引当 word 中的字符串结尾时再次为零。已达到。

关于c - C 语言的维吉尼亚密码 : Space not being ignored,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24087971/

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