在通过凯撒密码移动字母时,为什么我的代码会跳过空格和标点符号?

时间:2020-08-02 17:08:54

标签: c cs50

因此,我进行凯撒编程的代码是使用键将字母平移,但没有保留空格或标点符号。例如,如果用户在命令行中使用./caesar 2运行程序,并且他们想要“ A b”。要移动时,结果显示为“ Cd”,但应为“ C d”。我已经尝试解决此问题,但是我不知道如何解决。任何帮助,将不胜感激。我的代码在下面。

#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 key\n");

            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 key\n");
   }

}

3 个答案:

答案 0 :(得分:1)

您的循环基本上是这样的:

   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]);
       }
     }

答案 1 :(得分:0)

isalpha排除空格和标点符号。

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

答案 2 :(得分:0)

如果字符不是字母,则测试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");