Search code examples
encryptioncs50caesar-cipher

Encrypt a text using a key while preserving the case?


Task: Caesar’s algorithm (cipher (c)) encrypts messages by "rotating" each letter by key (k) positions.

To implement: ci = (pi+k)mod26 where ci is cipher, pi is plaintext and k is key.

My Pseudocode:

  1. Get key from command line argument.
  2. turn key (k) into integer.
  3. prompt user for plain text (pi)
  4. for each plain text character, preserve the case (using isalpha, isupper and islower functions in C.
  5. Finally shift plaintext character by key for example - "Go Home!" --- "Hp Ipnf!" (if key k =1, and preserving the upper/lower case of letters, ! remains as !). ** I am Struggling with this.
  6. Print ciphertext.

int main (int argc, string argv[]) //get key from command line argument        
     { 
      if (argc != 2 || atoi(argv[1]) < 0)
       { 
        printf ("print valid key");
        return 1;
       }

       int k = atoi(argv[1]);

       string p = get_string(); //prompt for plaintext

      for (int i=0, n = strlen(p); i < n; i++)
       { if (isalpha('p'))
        {
         if (isupper('p'))
         {
          printf ("%c", p[i]);
         }
         if (islower('p'))
         {
          printf ("%c", p[i]);
         }
        }
       }

     c[i]=(p[i]+k)%26;
      printf ("%c", c[i]);
     }

Solution

  • Actually ,the code you have written will simply return the value of plain text you have entered logic for this question is c[ i ]=( p[ i ] +k)%26 you have to make apply this formula differently for both upper and lower case I can give you a snippet of the code ,this will help you in solving your problem

    int l = (p[ i ] -65+k)%26 printf("%c",l+65);

    Here, k is the key In this I have used the ASCII values of the letters as the ASCII values is integer ,I have used a integer to store the value and apply the operation given . I have used 65 because ASCII value of upper case 'A' is 65. As we have to print the character we have used %c to print the character . This was for the upper case ,you can do similar with the lowercase If this answer was helpful , please click the arrow beside this Thank you :)