CS50 pset2 Vigenere代码 - 输出一个不正确的字母

时间:2015-07-31 17:39:03

标签: c vigenere cs50

此网站的新功能和编程。我已经查看了此主题下的前几个问题并尝试了许多修复,但我仍然遇到同样的问题。

我的程序运行正常并给出了我期望的输出,除了字母' B'或者' b'。其他所有字母都应该加密。我哪里出错了?

编辑 - 当我加密消息时,"在公园见我"用#34;培根"的钥匙,我应该得到:Negh zf av huf pcfx。相反,我得到:Tegh zf av huf pcfx

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

int main(int argc, string argv[])
{
    //Get key in commandline argument.  Prompt until key is given.
    string key = argv[1];
    int key_length = strlen(key);

    if (argc != 2)
    {
        printf("Invalid command. Please specify key.");
        return 1;
    }
    //Make sure only alphabetical chars are used in key.
    for (int i = 0; i < key_length; i++)
    {
        if (!isalpha(key[i]))
        {
        printf("Invalid command. Please specify key.");
        return 1;
        }
    }

    //Get message to be encrypted
    string plain = GetString();

    for (int i = 0, j = 0; i < strlen(plain); i++)
    {
        if (isalpha(plain[i]))
        {
            if (isupper(plain[i]))
            {
                plain[i] = (((plain[i] - 65) + (key[j%key_length] - 65)) % 26) + 65;
                j++;
            }
            else
            {
                if (islower(plain[i]))
                {
                plain[i] = (((plain[i] - 97) + (key[j%key_length] - 97)) % 26) + 97;
                j++;
                }
            }
        }
    }
    printf("%s\n", plain);
    return 0;
}

2 个答案:

答案 0 :(得分:1)

您假设明文字母与关键字母的情况相同。你没有正确编码大写字母M所看到的问题是因为这个原因。

首先将键中的所有字符转换为大写:

    if (!isalpha(key[i]))
    {
        printf("Invalid command. Please specify key.");
        return 1;
    } else {
        key[i]=toupper(key[i]);
    }

然后,当您进行编码时,假设密钥为大写。此外,不要为A和a添加或减去ASCII值,而只需使用字符常量。它使您的代码更具可读性。

您也不需要单独的isupperislower检查,因为您已经在之前的级别调用了isalpha

        if (isupper(plain[i]))
        {
            plain[i] = (((plain[i] - 'A') + (key[j%key_length] - 'A')) % 26) + 'A';
            j++;
        }
        else 
        {
            plain[i] = (((plain[i] - 'a') + (key[j%key_length] - 'A')) % 26) + 'a';
            j++;
        }

答案 1 :(得分:0)

有四种情况需要考虑

plain[i]    key[j]
------------------
 lower      lower
 lower      upper
 upper      lower
 upper      upper

您的代码只处理其中两种情况。

旁注:65应写为'A',类似地写入所有其他硬编码的数字。