Advertisement
JiriKiner

caesar.c

Sep 2nd, 2019
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.01 KB | None | 0 0
  1. // This program will encrypt the user's plaintext input to ciphertext using specified key (number)
  2.  
  3. // Included libraries
  4. #include <stdio.h>
  5. #include <cs50.h>
  6. #include <string.h>
  7. #include <ctype.h>
  8.  
  9. // We need to specify the user's key in the command-line
  10. int main(int argc, string argv[])
  11. {
  12.     // Ends the program with the error message if the user don't specify just one argument as a key
  13.     if (argc != 2)
  14.     {
  15.         printf("Usage: ./caesar key\n");
  16.         return 1;
  17.     }
  18.  
  19.     // Checks if each character of the given key is a digit, otherwise ends the program
  20.     int length = strlen(argv[1]);
  21.     for (int i = 0; i < length; i++)
  22.     {
  23.         if (isdigit(argv[1][i]) == false)
  24.         {
  25.             printf("Usage: ./caesar key\n");
  26.             return 1;
  27.         }
  28.     }
  29.  
  30.     // Changes the given argument to integer
  31.     int k = atoi(argv[1]);
  32.  
  33.     // If the given key is more than 25 (number of letters in alphabet), divide by 26 and use modulo instead (so the "wraparound" can work with "-26")
  34.     if (k > 25)
  35.     {
  36.         k = (k % 26);
  37.     }
  38.  
  39.     // Prompts for a plaintext
  40.     string pt = get_string("plaintext:  ");
  41.  
  42.     // Encrypts the plaintext by given key, excluding non-alphabet characters
  43.     int ptlength = strlen(pt);
  44.     char ct[ptlength];
  45.     for (int i = 0; i < ptlength; i++)
  46.     {
  47.         if (isalpha(pt[i]))
  48.         {
  49.             ct[i] = (pt[i] + k);
  50.         }
  51.         else
  52.         {
  53.             ct[i] = pt[i];
  54.         }
  55.     }
  56.  
  57.     // Wraparound from Z to A
  58.     for (int i = 0; i < ptlength; i++)
  59.     {
  60.         // For uppercase letters
  61.         if (isupper(pt[i]))
  62.         {
  63.             if (ct[i] > 90)
  64.             {
  65.                 ct[i] = (ct[i] - 26);
  66.             }
  67.         }
  68.         // For lowercase letters
  69.         else if (islower(pt[i]))
  70.         {
  71.             if (ct[i] > 122)
  72.             {
  73.                 ct[i] = (ct[i] - 26);
  74.             }
  75.         }
  76.     }
  77.     // Prints encrypted ciphertext
  78.     printf("ciphertext: %s\n", ct);
  79.     return 0;
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement