我在网上搜索了很长时间用于C语言的简单凯撒chiper /加密算法。 我发现了一个,但是并不完美,所以我已经改变了代码。 还有问题,因为朋友说程序应该能够处理大键。 例如带有键的文本“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çèä|
哪个错了......也许问题是字母/数组 - 我不知道......所以如果你可以帮助我,我会很高兴:)
这是源代码(带有一些注释):
#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;
}
答案 0 :(得分: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
}