简体   繁体   中英

caesar cipher does not work, can't figure why

I wrote my code and it seems fine, but there is something about it that just doesn't work and I can't figure out why. It is one caesar cipher but it just doesn't give me the expected output

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]);
        }
        }
    }
}

Incorrect handling when ptext[i] + key > 'z' .

'a' + (key % 26) does not depend on ptext[i]

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

Instead

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

Likewise for if (ptext[i] + key >= 'Z'){ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM