凯撒密码不工作,不知道为什么?

问题描述 投票:0回答:1

我写了我的代码,看起来很好,但有一些东西就是不工作,我想不出原因。这是一个凯撒密码,但它就是不给我预期的输出。

int main(int key, char* argv[])
{

key = atoi(argv[1]);
string ptext = get_string("plaintext: ");
int len = strlen(ptext);
printf("%s %i\n", ptext, key);`


    for (int i = 0; i < len; i++)
    {
        if (isalpha(ptext[i])){
            if (ptext[i] >= 'a' && ptext[i] <= 'z')
            {
                if (ptext[i] + key > 'z')
                {
                    printf("%c", 'a' + (key % 26)); //'a' is used to reset the ascii table so it use letters only
                }
                else{
                    printf("%c", ptext[i] + key);
                }
            if (ptext[i] >= 'A' && ptext[i] <= 'Z')
            {
                if (ptext[i] + key >= 'Z'){
                    printf("%c", (ptext[i] + (key % 26)) - 'z'); //'A' is used to reset the ascii table so it use letters only

                }
                else{
                    printf("%c", ptext[i] + key);
                }
                    }
            }
        else{
            printf("%c", ptext[i]);
        }
        }
    }
}
c caesar-cipher
1个回答
0
投票

处理不正确,当 ptext[i] + key > 'z'.

'a' + (key % 26) 不取决于 ptext[i]

if (ptext[i] + key > 'z') {
  printf("%c", 'a' + (key % 26)); // Incorrect. 
} else {
  ....
}

相反

int sum = (ptext[i] - 'a' + key)%26 + 'a';
printf("%c", sum);

同样,对于 if (ptext[i] + key >= 'Z'){.

© www.soinside.com 2019 - 2024. All rights reserved.