从昨天开始,我一直在研究这个问题,经过一番努力,我成功地加密了消息。但是,我的输出缺少空格。
据我了解,发生这种情况的原因是因为我正在使用 isalpha()、isupper() 和 islower() 命令,因此忽略了原始输入中的空格。
有人可以帮助我如何保留原始空格和标点符号吗?
下面是我的代码——它远非优雅,任何关于风格的评论也将不胜感激!
(此外,虽然有很多关于 Caesar Cipher 的问题,但没有一个可以解决这个问题。由于这是我的第一周编程,我很难理解其中的语法。)
我的算法中有一个明显的错误,如果给定某些参数,它会导致它输出错误的值。例如 ak 为 13,在第 13 个字母(我认为是 m)之后输入任何东西都会输出一些非常奇怪的东西。我会修改这个并很快回来!在那之前,对我的代码持保留态度!
# include <cs50.h>
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# include <ctype.h>
int main(int argc, string argv[])
{
if (argc != 2)
{
printf("Please enter a valid number of arguments! \n");
return 1;
}
string num = argv[1];
int k = atoi(num);
if (k < 0)
{
printf("Please enter a valid number! \n");
return 1;
}
printf("Please type the message which needs to be encrypted: ");
string p = GetString();
for (int i = 0, n = strlen(p); i < n; i++)
{
int oldletter = p[i];
int result1 = (oldletter + k);
int result2 = (oldletter - 65 + k);
int result3 = (result2) % 26;
int result4 = (oldletter - 97 + k);
int result5 = (result4) % 26;
if (isalpha(p[i]) && isupper(p[i]) && k < 26)
{
printf("%c", result1);
}
if (isalpha(p[i]) && isupper(p[i]) && k >= 26)
{
int result7 = (result3 + oldletter);
printf("%c", result7);
}
if (isalpha(p[i]) && islower(p[i]) && k < 26)
{
printf("%c", result1);
}
if (isalpha(p[i]) && islower(p[i]) && k >= 26)
{
int result8 = (result5 + oldletter);
printf("%c", result8);
}
}
printf("\n");
}
更正的代码,工作正常:SPOILERS AHEAD
# include <cs50.h>
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# include <ctype.h>
int main(int argc, string argv[])
{
if (argc != 2)
{
printf("Please enter a valid number of arguments! \n");
return 1;
}
string num = argv[1];
int k = atoi(num);
if (k < 0)
{
printf("Please enter a valid number! \n");
return 1;
}
printf("Message: ");
string p = GetString();
for (int i = 0, n = strlen(p); i < n; i++)
{
int oldletter = p[i];
int result1 = (oldletter - 65 + k);
int result2 = (result1) % 26;
int result3 = (oldletter - 97 + k);
int result4 = (result3) % 26;
if (isalpha(p[i]) && isupper(p[i]))
{
int result5 = (result2 + 65);
printf("%c", result5);
}
else if (isalpha(p[i]) && islower(p[i]))
{
int result6 = (result4 + 97);
printf("%c", result6);
}
else
{
printf("%c", p[i]);
}
}
printf("\n");
}