【问题标题】:Writing Vigenere Cipher in C (Keep Spaces)用 C 编写 Vigenere 密码(保留空格)
【发布时间】:2020-01-28 23:47:15
【问题描述】:

我正在尝试编写一个保留空格的 Vigenere Cipher (in c)。因此,如果给我一个简单的消息“你好,你好吗”,密码将采用这种形式“abcde fgh ijk lmn”,我想要的只是保留空格。我已经为此工作了一段时间。任何帮助,将不胜感激。

这是我的代码

void CipherText(char* plainText, char* cipherKey)
{
    int keyLength = strlen(cipherKey);
    char cipherText;

    for(int i = 0; i < strlen(plainText); i++)
    {

        int cipherText = (unsigned char)plainText[i];

        cipherText = ((int)plainText[i]-97+(int)tolower(cipherKey[i])-97)%26 + 'A';

        putchar(cipherText);
    }
    putchar('\n');
}

【问题讨论】:

  • 这段代码有什么问题?当前输出与您尝试的输出有何不同?
  • if (isalpha(cipherText)) { cipherText = … } — 仅在字符是字母时才转换字符(但无论如何都打印)。

标签: c cs50 vigenere


【解决方案1】:

在尝试转换(编码)字符之前测试字符是否是字母。另外,不要使用数字作为字符代码——例如,使用'a' 而不是97。我删除了一些不必要的演员表。我还使用了cipherText 而不是(int)plainText[i],因为这样可以避免不需要的符号扩展。我还添加了一些空格;明智地使用空格会更容易阅读代码。

void CipherText(char* plainText, char* cipherKey)
{
    int keyLength = strlen(cipherKey);
    char cipherText;

    for(int i = 0; i < strlen(plainText); i++)
    {
        int cipherText = (unsigned char)plainText[i];
        if (isalpha(cipherText))
            cipherText = (cipherText - 'a' + tolower(cipherKey[i]) - 'a') % 26 + 'A';
        putchar(cipherText);
    }
    putchar('\n');
}

【讨论】:

    猜你喜欢
    • 2018-07-29
    • 1970-01-01
    • 2016-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多