2
我想在C中實現Vigenere的密碼,但問題是,當我嘗試重複使用它在數組中使用的密鑰時,它會在第四個字母后中斷。所以如果密鑰是ABC並且明文是HELLO,它將返回HFNLO而不是HFNLP。當我查看我的代碼時,它邏輯上是有道理的,但它似乎不起作用。有人可以看到這個問題嗎?如何在數組中重複字符
下面是代碼:
int main(int argc, string argv[])
{
if(argc != 2)
{
printf("usage: ./vigenere k\n");
return 1;
}
//asks for plain text
printf("plaintext: ");
string text = get_string();
string k = argv[1];
printf("ciphertext: ");
//checks to see if length of key is shorter than length of plaintext and duplicates it.
int count = 0;
while(strlen(k) <= strlen(text))
{
k[strlen(k + count)] = k[count];
count++;
}
//changes key to be within 0 - 25 and encrypts plaintext
for(int i = 0; i < strlen(text); i++)
{
if(k[i] >= 'A' && k[i] <= 'Z')
{
k[i] = k[i] - 65;
}
else if (k[i] >= 'a' && k[i] <= 'z')
{
k[i] = k[i] - 97;
}
//if statement for plaintext capital letters
if(text[i] >= 'A' && text[i] <= 'Z')
{
text[i] = text[i] - 64;
text[i] = ((text[i] + k[i]) % 26) + 64;
}
//if statement for plaintext lowercase letters
else if(text[i] >= 'a' && text[i] <= 'z')
{
text[i] = text[i] - 96;
text[i] = ((text[i] + k[i]) % 26) + 96;
}
//prints final cipher
printf("%c", text[i]);
}
printf("\n");
return 0;
}
什麼是'k'?和'strlen(k + count)'絕對看起來很腥。 –
在密鑰索引上使用模數運算符,而不是此malarky。如'k [i%strlen(k)]'(爲了說明的目的:做更有效的事情)。 –