gpt4 book ai didi

c - Vigenere 问题集中的非字母问题

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

我刚刚解决了CS50中的Vigenere问题,但是仍然只有一个错误,即非字母字符,当你用纯文本编写任何没有空格、逗号、任何非字母的内容时,程序将运行良好,但是如果您写了任何非字母字符,例如空格,下一个字符将采用错误的键,这是我的代码:

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



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



// Make sure there is a command-line argment
if (argc != 2)
{
printf("Error\n");
return 1;
}

// Variables
int key[strlen(argv[1])];
string plaintext;


// Make sure the comman-line argment is Alphabets then make the key


for (int i = 0, n = strlen(argv[1]); i < n; i++)
{

if (!isalpha(argv[1][i]))
{
printf("Error 2\n");
return 1;
}

if (islower(argv[1][i]))
{
key[i] = argv[1][i] - 'a';
}

else if (isupper(argv[1][i]))
{
key[i] = argv[1][i] - 'A';
}
}





// Ask the user to write the message
plaintext = get_string("plaintext: ");
printf("ciphertext: ");



// Make sure the plaintext doesn't equal NULL
if (plaintext != NULL)
{


for (int i = 0, n = strlen(plaintext); i < n ; i++)
{

// Print in slower case
if (islower(plaintext[i]))
{
printf("%c", (((plaintext[i] + key[i % strlen(argv[1])]) - 'a') % 26) + 'a');
}

// Print in upper case
else if (isupper(plaintext[i]))
{
printf("%c", (((plaintext[i] + key[i % strlen(argv[1])]) - 'A') % 26) + 'A');
}

// Print the non alphabetic
else if (!isalpha(plaintext[i]))
{
printf("%c", plaintext[i]);
}


}
// Print a new line
printf("\n");
}
}

最佳答案

问题是因为您对明文和其中的 key 使用相同的索引
for (int i = 0, n = strlen(plaintext); i < n ; i++)环形。明文每移动一次, key 就会前进一位。显然这不是你想要的。您需要独立于该循环内的明文索引来管理 key 索引。

建议您重新观看the walkthrough也许可以像 Zamyla 写 Pandas 例子一样写出一个例子。学习如何使用 debug50 永远不会太早。如果我没记错的话,第二周有一个简短的内容。

CS50x has a stack forum致力于有关 CS50x 和 pset 的问题和解答。

关于c - Vigenere 问题集中的非字母问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54586351/

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