在没有看到您如何调用此函数的情况下,我构建了一些支持代码来调用此函数。我确定的是,当找到第一个字符的坐标时,您需要对嵌套在其中的第二个字符执行另一个循环测试,而不是像您的代码那样连续测试字符对中的第一个和第二个字符。以下是一些说明嵌套的重构代码。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char key[8][8] = { {'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', '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', '0', '1', '2', '3'},
{'4', '5', '6', '7', '8', '9', ' ', '.'},
};
void encrypt(char key[][8],char word[], char done[])
{
int x = 0, y = 0, t = 0, w = 0, z = 0, c=0;
while(word[c] != 0)
{
for(int j=0; j<8; j++)
{
for(int i=0; i<8; i++)
{
if(word[c]==key[i][j])
if(word[c + 1] == 0) /* Odd number of letters - switch and exit here */
{
done[c] = key[j][i];
done[c + 1] = 0; /* Tidy up */
return;
}
{
printf("i: %d, j: %d ", i, j); /* Nest the check of the second letter inside the first letter check */
for (int m = 0; m < 8; m++)
{
for (int n = 0; n < 8; n++)
{
if(word[c+1]==key[m][n])
{
printf("m: %d, n: %d \n", m, n);
w=m; /* Corrected per comments */
z=j;
x=i;
y=n;
}
}
}
}
done[c]=key[x][y];
done[c+1]=key[w][z];
if ((x == w) || (y == z)) /* Special case where either the letters are in the same row or same column */
{
done[c + 1]=key[x][y];
done[c]=key[w][z];
}
}
}
c=c+2;
}
}
int main()
{
char test_word[32];
char encrypted_word[32];
for (int i = 0; i < 32; i++)
{
encrypted_word[i] = 0;
}
strcpy(test_word, "Products");
encrypt(key, test_word, encrypted_word);
printf("Word: %s, Encrypted Word: %s\n", test_word, encrypted_word);
strcpy(test_word, encrypted_word);
for (int i = 0; i < 32; i++)
{
encrypted_word[i] = 0;
}
encrypt(key, test_word, encrypted_word);
printf("Word: %s, Encrypted Word: %s\n", test_word, encrypted_word);
return 0;
}
由于理论上,通过这个函数放置加密词应该解密这个词,所以我只是使用特定的文字词调用了两次函数来测试。以下是我终端上的输出证明了这个理论。
@Una:~/C_Programs/Console/Encryption/bin/Release$ ./Encryption
i: 1, j: 7 m: 5, n: 3
i: 5, j: 0 m: 3, n: 5
i: 5, j: 6 m: 3, n: 4
i: 5, j: 5 m: 5, n: 4
Word: Products, Encrypted Word: d5rFj1lt
i: 3, j: 5 m: 7, n: 1
i: 5, j: 3 m: 0, n: 5
i: 4, j: 3 m: 6, n: 5
i: 4, j: 5 m: 5, n: 5
Word: d5rFj1lt, Encrypted Word: Products
【讨论】:
- <1234563>