我正在学习这个免费的在线课程,所以资源和帮助是相当有限的。他们想要一个 Vigenere 密码。我的代码正在通过所有测试,我认为它已经完成,直到我输入“ho1W are y0Ou?”作为文本和“heLLo”作为它们的键。执行是完美的,除了小写的 u 不会继续通过 'z' - 'a'循环,而是打印'''。代码确实在“how”中的“W”和“you”中的“y”中成功执行了“z”到“a”循环。关键,“heLLo”是确实重复成功并且当它碰到'u'时不在strlen的末尾。它也不会在非字母字符上增加1。我不知道从这一点开始。任何人都可以提供一些建议?谢谢!
#include <cs50.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
// Function to get string (text) from user
string Encrypt(void);
int main(int argc, string argv[])
{
// Exits with improper arguement count
if (argc != 2)
{
printf("You must enter one keyword when running the program.\n");
return 1;
}
// Sets key entered for command argument 1
string key = argv[1];
// Checks key to make sure a-z is entered. Exits if not.
for (int i = 0, word = strlen(key); i < word; i++)
{
if (isalpha(key[i]))
{
}
else
{
printf("Only letters are allowed for the key.\n");
return 1;
}
}
string text = Encrypt();
// Secret used to print out final message
char secret = 'a';
// K contorls array place in key
int k = 0;
// If text is entered and alpha: compares text[i] and key[k]
if (text != NULL)
{
for (int i = 0, len = strlen(text); i < len; i++)
{
if (isalpha(text[i]))
{
// Checks k poition to make sure it is within array
if (k == strlen(key))
{
k = 0;
}
// Converts key if text is lowercase
if (islower(text[i]))
{
secret = (((text[i] - 'a') + (key[k] - 'a')) % 26) + 'a';
printf("%c", tolower(secret));
}
// Converts key if text is uppercase
if (isupper(text[i]))
{
secret = (((text[i] - 'A') + (key[k] - 'A')) % 26) + 'A';
printf("%c", toupper(secret));
}
k++;
}
// If not alpha ignores loop and prints text char.
else
{
printf("%c", text[i]);
}
}
}
return 0;
}
string Encrypt(void)
{
printf("Enter your text.");
string text = GetString();
return text;
}