string text = GetString();
//enters length of argv string into q
//converts string argv[1] into string key
string key = argv[1];
int klen = strlen(key);
int kposition = 0;
//loop through the characters in array "text"
for (int tposition = 0, n = strlen(text); tposition < n; tposition ++)
{
if isupper(key[kposition])
{
key[kposition] = ((key[kposition] - 'A') % klen) + 'A';
}
else if islower(key[kposition])
{
key[kposition] = ((key[kposition] - 'a') % klen) + 'a';
}
//determine if character is alphabetical
if (isalpha(text[tposition]))
{
//encrypt upper case characters
if (isupper(text[tposition]))
{
//modulo magic to loop to beginning of alphabet after 'Z'
text[tposition] = (((text[tposition] - 'A') + key[kposition]) % 26) + 'A';
printf("%c", text[tposition]);
}
//encrypt lower case characters
else
{
//modulo magic to loop to beginning of alphabet after 'z'
text[tposition] = (((text[tposition] - 'a') + key[kposition]) % 26) + 'a';
printf("%c", text[tposition]);
}
}
//if the input isn't alphabetical, then just print the input (spaces)
else
{
printf("%c", text[tposition]);
}
kposition ++;
}
printf("\n");
return 0;
我按照您的建议将变量更加具体化,这有助于我查看代码。
尽管程序编译和运行正常,但我仍然无法获得正确的输出。
例如,当我运行: vigenere.c -bacon
并输入:“Meet me at the park”, 我得到的是:“Gxzq mr ni kyr frea”,而不是正确的答案:“Negh zf av huf pcfx”。
因此,大小写字母和空格都没有问题。问题出在key [kposition]的增量上。问题的一部分是我不太理解模数,因此不清楚模算术在做什么(除了给出两个数字的余数)。
如何更好地安排我的key [kposition]增量器?