-1

本网站和编程新手。我已经查看了该主题下的先前问题并尝试了任意数量的修复,但我一直遇到同样的问题。

我的程序运行良好,并给出了我期望的输出,但字母“B”或“b”除外。其他所有字母都按应有的方式加密。我哪里做错了?

编辑 - 当我用“培根”密钥加密消息“在公园见我”时,我应该得到: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;
}
4

2 回答 2

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++;
        }
于 2015-07-31T18:11:59.810 回答
0

有四种情况需要考虑

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

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

旁注:对于所有其他硬编码数字,65应以类似方式编写。'A'

于 2015-07-31T18:11:52.740 回答