DragonOsman

Caesar Cipher

Oct 13th, 2016
211
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.55 KB | None | 0 0
  1. // Osman Zakir
  2. // 10 13 2016
  3. // Introduction to Computer Science
  4. // Problem Set 2, caesar.c
  5. // Take the key for the cipher from the user as a command-line argument and use it to encrypt a message
  6.  
  7. #include <cs50.h>
  8. #include <stdio.h>
  9. #include <string.h>
  10. #include <ctype.h>
  11. #include <stdlib.h>
  12. #include <math.h>
  13.  
  14. int main(int argc, string argv[])
  15. {
  16.     if (argc == 1 || argc > 2)
  17.     {
  18.         printf("Error: Please input one number to use as key for cipher!\n");
  19.         return 1;
  20.     }
  21.     printf("Enter plaintext to be shifted by %d positions\n", atoi(argv[1]));
  22.     string plaintext = GetString();
  23.     int key = atoi(argv[1]);
  24.     const int size = strlen(plaintext);
  25.     char ciphertext[size];
  26.     if (key >= pow(2, 31) - 26 || key <= 0)
  27.     {
  28.         printf("The value for the key is invalid!\n");
  29.     }
  30.     else
  31.     {
  32.         for (int i = 0, n = size; i < n; i++)
  33.         {
  34.             if (isalpha(plaintext[i]))
  35.             {
  36.                 //int c = plaintext[i] + key;
  37.                
  38.                 ciphertext[i] = plaintext[i] + key;
  39.                 if (plaintext[i] >= 'Z' && isupper(plaintext[i]))
  40.                 {
  41.                     ciphertext[i] = ((plaintext[i] + key) - 'A') % 26;
  42.                 }
  43.                 else if (plaintext[i] >= 'z' && islower(plaintext[i]))
  44.                 {
  45.                     ciphertext[i] = ((plaintext[i] + key) + 'a') % 26;
  46.                 }
  47.                 /*if (plaintext[i] >= 'z')
  48.                 {
  49.                     ciphertext[i] = 'a' + (c % ('a' + 26));
  50.                 }
  51.                 else if (plaintext[i] >= 'Z')
  52.                 {
  53.                     ciphertext[i] = 'A' + (c % ('A' + 26));
  54.                 }*/
  55.             }
  56.             else
  57.             {
  58.                 ciphertext[i] = plaintext[i];
  59.             }
  60.         }
  61.     }
  62.     printf("%s\n", ciphertext);
  63.     return 0;
  64. }
Add Comment
Please, Sign In to add comment