C Caesar Cipher - 大键错误

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

我在网上搜索了很长一段时间,用C语言编写了一个简单的caesar chiper / encryption算法。我发现了一个,但是并不完美,所以我已经改变了代码。还有问题,因为朋友说程序应该能够处理大键。例如带有键的文本“Hello World”:50 ...如果我这样做,我会得到以下内容:(控制台输出)

This tiny application encodes plain text to the Caesar Encryption
Type in some text to decode: Hello World
Type in the key/shifting of the letters:
50
`}ääç oçèä|

这是错误的......也许问题是char /数组 - 我不知道......所以如果你可以帮助我,我会很高兴:)

这是源代码(带一些注释):

#include <stdio.h>
#include <conio.h>
#include <wchar.h>

int main()
{
unsigned char array[100], shifting; //creating 2 arrays for the encryption
//I changed it to unsigned char because otherwise Z with key 6/7 dosen't work
int z; //This is our key
printf("This tiny application encodes plain text to the Caesar Encryption\n");

printf("Type in some text to decode :");
fgets(array, 100, stdin); //because gets() is bad I'am using fgets()
printf("Type in the key/shifting of the letters:\n");
scanf("%d", &z);

for (int i = 0; array[i] != '\0'; i++) 
{
    shifting = array[i]; //overgive values from array to shifting
    if (shifting >= 'a' && shifting <= 'z') { //check the containing lowercase letters
        shifting = shifting + z;

        if (shifting > 'z') {
            shifting = shifting - 'z' + 'a' - 1; // if go outside the ascii alphabeth this will be done
        }

        array[i] = shifting;
    }
    else if (shifting >= 'A' && shifting <= 'Z') { //the same for uppercase letters
        shifting = shifting + z;

        if (shifting > 'Z') {
            shifting = shifting - 'Z' + 'A' - 1;
        }

        array[i] = shifting;
    }
}

printf("%s\n", array);

return 0;
}
c arrays ascii caesar-cipher
1个回答
2
投票

问题的根源在这里:

    if (shifting > 'z') {
        shifting = shifting - 'z' + 'a' - 1; // if go outside the ascii alphabeth this will be done
    }

英文字母的长度是多少?这是26岁。

如果你给z大于26,单个字母长度的减量是不够的。您应该确保z不超过字母表的长度,重复递减直到结果符合字母表范围。

解决方案1:

    int asciiAlphabetLength = 'z' - 'a' + 1;

    printf("Type in the key/shifting of the letters:\n");
    scanf("%d", &z);
    z %= asciiAlphabetLength;

解决方案2:

    shifting += z;

    while (shifting > 'z') {
        shifting -= asciiAlphabetLength; // while outside the ascii alphabeth reduce
    }
© www.soinside.com 2019 - 2024. All rights reserved.