好的,我刚刚开始我的C世界之旅,所以我和我一起。
我正在尝试实现Vigenere Cipher,但在尝试循环密钥时遇到问题。首先,所有的小功能,虽然,我不认为问题存在。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define ALPHANUMERIC "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" /* all alphabetic characters at their corresponding indices */
char* squeeze(char[], int);
char* formatString(char[]);
int findindex(char c);
/* squeeze: remove all occurences of c in s */
char* squeeze(char s[], int c)
{
int i, j;
for (i = j = 0; s[i] != '\0'; i++)
if (s[i] != c)
s[j++] = s[i];
s[j] = '\0';
// printf("%s\n", s);
return s;
}
/* formatString: remove all white spaces and special
characters and convert all letters to upper case */
char* formatString(char input[])
{
int i;
input = squeeze(input, ' ');
for (i = 0; input[i] != '\0'; i++)
{
if (!isalnum(input[i]))
{
input = squeeze(input, input[i]);
--i;
}
if (islower(input[i]))
input[i] = toupper(input[i]);
}
// printf("%s\n", input);
return input;
}
/* findindex: returns the predefined index of a given character */
int findindex(char c)
{
int i;
if (isdigit(c))
return 26 + c - '0';
for (i = 0; ALPHANUMERIC[i] != '\0'; i++)
if (c == ALPHANUMERIC[i])
return i;
return -1;
}
这是密码功能。为了澄清,我的想法是循环遍历for循环中的文本字符串,并使用j计数器通过将代码字设置为零来循环遍历代码字,当它到达代码字的末尾时。所有额外的printf都用于调试目的。
void cipher(char codeword[], char text[])
{
int i, j;
char newword[strlen(text)];
codeword = formatString(codeword);
text = formatString(text);
printf("codeword = %s, text = %s\n", codeword, text );
j = -1;
for (i = 0; i < strlen(text); i++)
{
j++;
printf("text[i] = %c, %d, codeword = %c, %d\n", text[i], findindex(text[i]), codeword[i], findindex(codeword[i]));
newword[i] = ALPHANUMERIC[(findindex(text[i]) + findindex(codeword[j])) % 36];
printf("i = %d, j = %d\n", i, j);
if (j == strlen(codeword) - 1)
j = -1;
}
printf("%s\n", newword);
}
所以,看看代码,一切看起来都很好,直到我运行它。这是输入“ivcho”,“ivayloivayloo”的输出:
codeword = IVCHO, text = IVAYLOIVAYLOO
text[i] = I, 8, codeword = I, 8
i = 0, j = 0
text[i] = V, 21, codeword = V, 21
i = 1, j = 1
text[i] = A, 0, codeword = C, 2
i = 2, j = 2
text[i] = Y, 24, codeword = H, 7
i = 3, j = 3
text[i] = L, 11, codeword = O, 14
i = 4, j = 4
text[i] = O, 14, codeword = , -1
i = 5, j = 0
text[i] = I, 8, codeword = , -1
i = 6, j = 1
text[i] = V, 21, codeword = , -1
i = 7, j = 2
text[i] = A, 0, codeword = , -1
i = 8, j = 3
text[i] = Y, 24, codeword = G, 6
i = 9, j = 4
text[i] = L, 11, codeword = C, 2
i = 10, j = 0
text[i] = O, 14, codeword = C, 2
i = 11, j = 1
text[i] = O, 14, codeword = :, -1
i = 12, j = 2
QGC5ZW3XHCT9Q
当计数器(j)设置为零时,它不会重新开始,我不知道为什么。
我知道这远不是密码的最聪明的解决方案,但我真的想让它工作,所以我很感激你的帮助。