本网站和编程新手。我已经查看了该主题下的先前问题并尝试了任意数量的修复,但我一直遇到同样的问题。
我的程序运行良好,并给出了我期望的输出,但字母“B”或“b”除外。其他所有字母都按应有的方式加密。我哪里做错了?
编辑 - 当我用“培根”密钥加密消息“在公园见我”时,我应该得到:Negh zf av huf pcfx。相反,我得到: Tegh zf av huf pcfx
#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(int argc, string argv[])
{
//Get key in commandline argument. Prompt until key is given.
string key = argv[1];
int key_length = strlen(key);
if (argc != 2)
{
printf("Invalid command. Please specify key.");
return 1;
}
//Make sure only alphabetical chars are used in key.
for (int i = 0; i < key_length; i++)
{
if (!isalpha(key[i]))
{
printf("Invalid command. Please specify key.");
return 1;
}
}
//Get message to be encrypted
string plain = GetString();
for (int i = 0, j = 0; i < strlen(plain); i++)
{
if (isalpha(plain[i]))
{
if (isupper(plain[i]))
{
plain[i] = (((plain[i] - 65) + (key[j%key_length] - 65)) % 26) + 65;
j++;
}
else
{
if (islower(plain[i]))
{
plain[i] = (((plain[i] - 97) + (key[j%key_length] - 97)) % 26) + 97;
j++;
}
}
}
}
printf("%s\n", plain);
return 0;
}