我正在学习这个免费的在线类(class),因此资源和帮助相当有限。他们想要维吉尼亚密码。我的代码通过了所有测试,我认为它已经完成,直到我输入“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;
}
最佳答案
问题是当它到达字符串中的“u”时,您就位于 key 中的“L”上。所以当这段代码运行时:
secret = (((text[i] - 'a') + (key[k] - 'a')) % 26) + 'a';
通过替换,你有:
secret = ((('u' - 'a') + ('L' - 'a')) % 26) + 'a';
提示:'L' - 'a' = -21。 'u' - 'a' = 20。希望你能从这里算出剩下的,祝你好运。
关于c - C 中的数组比较和循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22548603/