Advertisement
ssoni

caesar.c

Feb 16th, 2022
1,321
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.93 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <cs50.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <ctype.h>
  6.  
  7. int main(int argc, string argv[])
  8. {
  9.     if (argc != 2)
  10.     {
  11.         printf("USAGE: ./caesar NUM\n");
  12.         return 1;
  13.     }
  14.  
  15.     //get offset value from cmdline args
  16.     int offset=0;
  17.     offset = atoi(argv[1]);
  18.  
  19.     for (int i=0; i<strlen(argv[1]); i++)
  20.     {
  21.         if (isdigit(argv[1][i]) == 0)
  22.         {
  23.             printf("USAGE: ./caesar NUM\n");
  24.             return 1;
  25.         }
  26.     }
  27.  
  28.     //adjust for offset greater than 26 (redundant cycles)
  29.     //eg: offset of 27 is just offset of 1.  Eliminate lap of 26.
  30.     offset = offset % 26;
  31.  
  32.     //get text to encode
  33.     string plaintext;
  34.     plaintext = get_string("plaintext: ");
  35.  
  36.     printf("ciphertext: ");
  37.  
  38.     int shift=0;
  39.     //loop thru and encode each letter
  40.     for (int i=0; i<strlen(plaintext); i++)
  41.     {
  42.         if (isupper(plaintext[i]) != 0)
  43.         {
  44.             shift = 64;
  45.             plaintext[i] = plaintext[i] - shift;    //shift letters down to 1-26
  46.             plaintext[i] = plaintext[i] + offset;   //add the caesar encryption offset
  47.             plaintext[i] = plaintext[i] % 26;       //Rotate around z to a (eg: 27 becomes 1)
  48.             plaintext[i] = plaintext[i] + shift;    //shift letters back up
  49.             printf("%c", plaintext[i]);
  50.         }
  51.         else if (islower(plaintext[i]) != 0)
  52.         {
  53.             shift = 96;
  54.             plaintext[i] = plaintext[i] - shift;    //shift letters down to 1-26
  55.             plaintext[i] = plaintext[i] + offset;   //add the caesar encryption offset
  56.             plaintext[i] = plaintext[i] % 26;       //Rotate around z to a (eg: 27 becomes 1)
  57.             plaintext[i] = plaintext[i] + shift;    //shift letters back up
  58.             printf("%c", plaintext[i]);
  59.         }
  60.         else
  61.         {
  62.             printf("%c", plaintext[i]);
  63.         }
  64.     }
  65.     printf("\n");
  66. }
  67.  
  68.  
  69.  
  70.  
  71.  
  72.  
  73.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement