CS50x 2019 pset2:Vigenère无法完全正常工作

时间:2019-08-07 16:27:25

标签: cs50 vigenere

我目前正在研究CS50x 2019的pset2,尤其是Vigenère。将CS50成绩册上传到GitHub后,我的成绩达到了93%。

我已经尝试了一些其他代码片段,可以在网上找到它们,但是它们似乎没有用。

这是我的程序中创建密文的部分:

    string k = argv[1];
    // Get the plaintext and print out the ciphertext
    string s = get_string("plaintext: ");
    printf("ciphertext: ");

    // Iterate through plaintext letter by letter
    for (int i = 0, n = strlen(s) ; i < n; i++)
    {
        int key = tolower(k[i % strlen(k)]) - 'a';

        // Check if the letter is lowercase, uppercase or neither and print out the rotated character
        if (islower(s[i]))
        {
            printf("%c", (((s[i] - 'a') + key) % 26) + 'a');
        }
        else if (isupper(s[i]))
        {
            printf("%c", (((s[i] - 'A') + key) % 26) + 'A');
        }
        else
        {
            printf("%c", s[i]);
        }
    }

    printf("\n");
    return 0;

文档中有一些示例,您可以使用代码进行测试。

以下示例不适用于我的代码:

$ ./vigenere bacon
plaintext:  Meet me at the park at eleven am
ciphertext: Negh zf av huf pcfx bt gzrwep oz

我的输出是:

$ ./vigenere bacon
plaintext: Meet me at the park at eleven am
ciphertext: Negh ne og tjs qaty bt syfvgb bm

如您所见,前4个字符是正确的,但其余的不是。

1 个答案:

答案 0 :(得分:0)

这个int key = tolower(k[i % strlen(k)]) - 'a';是个问题。

根据规格:

  

还请记住,每次加密字符时,都需要   移至关键字的k的下一个字母(然后环绕到   如果您用尽了所有字符,则以关键字开头)。但是如果   您没有加密字符(例如空格或标点符号),   不要前进到k的下一个字符!

最重要的是:由于plaintextkey以不同的“速率”运行,因此您不能为两者使用相同的索引(在这种情况下为i)。程序应一次抓取plaintext一个字符,如此处所示。但是,它需要一种单独的方法来控制key中的字符,因此您可以1)跳过空格/标点符号和2)环绕。 key索引的另一个变量将是解决它的一种方法。代码中可能还存在其他问题,但这是一个基本缺陷。

相关问题