试图进行凯撒密码。
enum alfabeto{
A=0,B,C,D,E,F,G,H,I,L,M,N,O,P,Q,R,S,T,U,V,Z // 21
};
void cifra(char *string, int k){
enum alfabeto letter; // initialize the enum letter
size_t i = 0; // initialize counter
while (*(string+i)!='\0'){ // while string is not ended
letter = *(string+i); // attempt to "link" the enum letter to the equivalent (already uppercased) char
printf("%d", letter);
letter = (letter+k) % 21; // then it increases of a factor k and if it goes out of 21, it should take the right value
printf(" %d\n", letter);
++i;
}
}
输出:
$ ./"cesare"
write the text:
>TEST
choose the factor k:
>2
84 8
69 14
83 7
84 8
值是错误的...可能是因为我无法将枚举值“链接”到字符...我该怎么办?c
答案 0 :(得分:0)
letter = *(string+i); // attempt to "link" the enum letter to the equivalent (already uppercased) char
应该是:
letter = *(string+i) - 'A'; // attempt to "link" the enum letter to the equivalent (already uppercased) char
这样,“ A
”将根据需要映射为零。
答案 1 :(得分:0)
// A B C D E F G H I J K L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z
const int offsetTable[] = {0,1,2,3,4,5,6,7,8,-1,-1,9,10,11,12,13,14,15,16,17,18,19,-1,-1,-1,20};
const char charLookupTable[] = "ABCDEFGHILMNOPQRSTUVZ";
// Should probably use a struct for the above to prevent size mis-matches
const int offsetTableSize = 21;
void cifra(char *str, int k){
char letter;
int newLetterOffset;
printf("%s\n", str); // Show initial string.
while (letter = *str++){ // while string is not ended
const int oldLetterOffset = offsetTable[letter - 'A']; // Get the old letter's offset.
if(letter <= 'A' || letter >= 'Z' || oldLetterOffset == -1)
{
printf("\nBad character %c found - ending string processing\n", letter);
return;
}
newLetterOffset = (oldLetterOffset + k) % offsetTableSize; // Get the letter's position, add the global offset, and wrap to table size.
printf("%c", charLookupTable[newLetterOffset]); // Use that offset to read the character's value from the shortened alphabet.
}
printf("\n\n");
}
int main()
{
cifra("HELLO", 0);
cifra("HELLO", 1);
cifra("HELLo", 1);
cifra("YELLO", 1);
return 0;
}
注意,我需要2个表来完成这项工作,因为我们不得不进出缩短的字符集。通常,我们将使用一个结构来保存这两个数组,但是在此示例中,我将其保持简单。另外,数组不必是全局的,但我也将它们放在那里以使事情更简单。
注意,我还更改了您的printf()值,以使用字符和字符串以使其更易于阅读。
最后,我添加了一些错误检查,因为您不能信任用户为您提供良好的字符串。由此导致许多安全漏洞或随机崩溃。