gpt4 book ai didi

c - 维吉尼亚密码

转载 作者:行者123 更新时间:2023-11-30 21:08:25 28 4
gpt4 key购买 nike

我在运行下面为 vigenere cipher 设计的代码时遇到问题。即使彻底检查后我也无法调试问题。它显示错误:被服务器杀死。请帮忙。

 /**
*
* vigenere.c
*
* Abhishek kumar
* encrypts entered string using vigenere cipher
* */
#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>

int main(int argc, string argv[] )
{
if (argc != 2)
{
printf("Usage: /home/cs50/pset2/vigenere <keyword>");
return 1;
}

if (argc == 2)
{ string key = argv[1];
for(int k = 0,l = strlen(key);k < l; k++)
{
if(!isalpha(key[k]))
{
printf("Keyword must only contain letters A-Z and a-z");
exit(1);
}

}


string txt = GetString();
int i = 0,j = 0,c = 0;
int n = strlen(txt);
int m = strlen(key);
while(i < n)
{
if (isupper(txt[i]))
{
if(isupper(key[j]))
{
c = ((((int) txt[i] - 65 + (int) key[j] -65)%26) + 65);
printf("%c", (char) c);
i++;
j++;
}
if(islower(key[j]))
{
c = ((((int) txt[i] - 65 + (int) key[j] -97)%26) + 65);
printf("%c", (char) c);
i++;
j++;
}

}
else if (islower(txt[i]))
{
if(isupper(key[j]))
{
c = ((((int) txt[i] - 97 + (int) key[j] -65)%26) + 97);
printf("%c", (char) c);
i++;
}
if(islower(key[j]))
{
c = ((((int) txt[i] - 97 + (int) key[j] -97)%26) + 97);
printf("%c", (char) c);
j++;
}


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

}
if (j == m-1)
{
j = 0;
}
}




}
}

下面是一些失败的测试用例。

:) vigenere.c exists
:) vigenere.c compiles
:( encrypts "a" as "a" using "a" as keyword
\ killed by server
:( encrypts "world, say hello!" as "xoqmd, rby gflkp!" using "baz" as keyword
\ killed by server
:( encrypts "BaRFoo" as "CaQGon" using "BaZ" as keyword
\ expected output, but not "CGSFpp"
:( encrypts "BARFOO" as "CAQGON" using "BAZ" as keyword
\ expected output, but not "CASFPO"
:) handles lack of argv[1]
:) handles argc > 2
:) rejects "Hax0r2" as keyword

最佳答案

islower(txt[i]) 部分中,在所有情况下都无法递增 ij。在不增加 i 的地方,即键的第一个字符和文本都是小写的地方,最终会出现无限循环。

isupper(txt[i]) 部分中,您在 isupper(key[j ]) 部分,然后输入 islower(key[j]) 部分,因为您使用 if 而不是 else if

对于上述两者,将 if(islower(key[j])) 更改为 else if(islower(key[j])),然后移动 j++ 和每个内部 if block 后面的 printf。至于 i,将 while 更改为 for 并递增 i 作为其中的一部分。

当检查是否应该重置 j 时,您落后了 1。m-1key 的有效索引所以你还不想重置。当j == m时执行此操作。

此外,将 ASCII 代码替换为它们所代表的实际字符,以便更清楚您在做什么。也不需要强制转换。

    for (i=0; i < n; i++)
{
if (isupper(txt[i]))
{
if(isupper(key[j]))
{
c = (((txt[i] - 'A' + key[j] -'A')%26) + 'A');
}
else if(islower(key[j]))
{
c = (((txt[i] - 'A' + key[j] -'a')%26) + 'A');
}
printf("%c", c);
j++;
}
else if (islower(txt[i]))
{
if(isupper(key[j]))
{
c = (((txt[i] - 'a' + key[j] -'A')%26) + 'a');
}
else if(islower(key[j]))
{
c = (((txt[i] - 'a' + key[j] -'a')%26) + 'a');
}
printf("%c", c);
j++;
}
else
{
printf("%c",txt[i]);
}
if (j == m)
{
j = 0;
}
}

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

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