c-为什么我的代码在通过凯撒密码转换字母时跳过空格和标点符号



因此,我的caesar编程代码用键移动字母很好,但没有保留空格或穿孔。例如,如果用户使用运行程序/凯撒2号在命令行,他们想要";A.";为了被移位;Cd";,但它应该是";C;。我试过解决这个问题,但就是不知道怎么解决。如有任何帮助,我们将不胜感激。我的代码在下面。

#include <stdio.h>
#include <cs50.h>
#include <math.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, string argv[])
{
string plain = NULL;
char num1;
char halftotal;
char total;

//creating the key
if(argc == 2)
{
int shift = atoi(argv[1]);
if(shift < 0)
{
printf("Usage: ./caesar keyn");
return 1;
}
else if(shift > 0)
{
//prompting for plaintext
plain = get_string("Plaintext: ");
//enciphering plaintext
int test = strlen(plain);
printf ("Ciphertext: ");
for( int i = 0;i < test;i++)
{
if(isalpha(plain[i]))
{
if(isupper(plain[i]))
{
num1 =  plain[i] - 65;
halftotal = (num1 + shift)%26;
total = (halftotal + 65);
printf("%c", total);
}
else if(islower(plain[i]))
{
num1 =  plain[i] - 97;
halftotal = (num1 + shift)%26;
total = (halftotal + 97);
printf("%c", total);
}
}
}
printf("n");
return 0;
}
}
else if(argc != 2)
{
printf("Usage: ./caesar keyn");
}
}

您的循环基本上如下所示:

for( int i = 0;i < test;i++)
{
if(isalpha(plain[i]))
{
// convert the character
...
}
}

所以当这个字符是一个字母时,你要进行转换。但如果不是,你什么也不做。这就是为什么在输出中除了字母之外什么都看不到的原因。

您需要在这里添加一个else子句,以简单地打印给定的内容(如果不是字母(。

for( int i = 0;i < test;i++)
{
if(isalpha(plain[i]))
{
// convert the character
...
}
else
{
printf("%c", plain[i]);
}
}

如果字符不是按字母顺序排列的,则测试if(isalpha(plain[i]))不会执行任何其他操作,因此它被忽略。

你可以删除它并在下面添加else printf("%c", plain[i]);,这样代码的一部分看起来像这个

printf ("Ciphertext: ");
for( int i = 0;i < test;i++) 
{
if(isupper(plain[i]))
{
num1 =  plain[i] - 'A';         // replaced magic numbers too       
halftotal = (num1 + shift) % 26;
total = (halftotal + 'A');
printf("%c", total);
}
else if(islower(plain[i]))
{
num1 =  plain[i] - 'a';
halftotal = (num1 + shift) % 26;
total = (halftotal + 'a');
printf("%c", total);
}
else 
{
printf("%c", plain[i]);
}
}
printf("n");

isalpha排除空白和标点符号。

http://cplusplus.com/reference/cctype/isalpha/

最新更新