我一直在研究这个Vigenere密码大约8个小时。你能帮我么?我认为主要问题在于算法 - 我不知道如何利用密钥长度(我知道我需要以某种方式得到它的mod)。
#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char *argv[])
{
if(argc != 2)
{
printf("Bad!");
return 1;
}
int keylen = strlen(argv[1]);
char *key = argv[1];
for (int i = 0; i < keylen; i++)
{
if(isupper(key[i]))
{
key[i] = key[i]-65;
}
else if(islower(key[i]))
{
key[i] = key[i]-97;
}
}
printf("Plaintext: ");
string p = GetString();
int k = 0;
for (int i = 0; i < strlen(p); i++)
{
if(isalpha(p[i]))
{
if(isupper(p[i]))
{
p[i] = ((p[i]-65)+(key[k % keylen]))%26 + 65;
}
else if(islower(p[i]))
{
p[i] = ((p[i]-97)+(key[k % keylen]))%26 + 97;
}
k++;
}
else
{
//I need to skip over antyhing that isn't a letter
p[i] = p[i];
}
}
printf("Ciphertext: %s\n", p);
}
答案 0 :(得分:3)
第一个for
循环有问题。条件是检查i > keylen
何时应检查i < keylen
。
同样在计算下一个输出值时,步骤应为
(p[i]-'A') results in a number between 0 and 25
adding (key[i % keylen]) results in a number between 0 and 50
apply modulo 26 so the number is between 0 and 25 (this is the missing step)
then add 'A' to get the output
注意:避免使用硬编码的数字作为字符常量。例如,使用'A'
代替65,使用'a'
代替97。