Advertisement
Guest User

substitution.c

a guest
Aug 1st, 2021
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.09 KB | None | 0 0
  1. #include <cs50.h>
  2. #include <ctype.h>
  3. #include <stdio.h>
  4. #include <string.h>
  5.  
  6. int main(int argc, string argv[])
  7. {
  8.     // Validate key length
  9.     if (argc == 2)
  10.     {
  11.         string key = argv[1];
  12.         int key_len = strlen(key);
  13.  
  14.         // Check key is 26 characters, and alphabetic
  15.         for (int i = 0, n = key_len; i < key_len; i++)
  16.         {
  17.             if (key_len < 26 && isalpha(key[i]))
  18.             {
  19.                 printf("Key must contain 26 characters.\n");
  20.                 return 1;
  21.             }
  22.             if (key_len > 26 && isalpha(key[i]))
  23.             {
  24.                 printf("Key must contain 26 characters.\n");
  25.                 return 1;
  26.             }
  27.         }
  28.  
  29.  
  30.         // Reject digits
  31.         int j = 0;
  32.         if (isdigit(key[j]))
  33.         {
  34.             printf("Usage: ./substitution key\n");
  35.             return 1;
  36.         }
  37.  
  38.         // Check for duplicate letters
  39.         for (int q = 0; q < key_len; q++)
  40.         {
  41.             for (int w = q + 1; w < key_len; w++)
  42.             {
  43.                 if (key[q] == key[w])
  44.                 {
  45.                     printf("Key must not contain repeated characters.\n");
  46.                     return 1;
  47.                 }
  48.             }
  49.         }
  50.  
  51.  
  52.         // Collect plaintext
  53.         string s = get_string("plaintext: ");
  54.  
  55.         // Output encrypted text
  56.         printf("ciphertext: ");
  57.         for (int o = 0, m = strlen(s); o < m; o++)
  58.         {
  59.             if (isalpha(s[o]) && isupper(s[o]))
  60.             {
  61.                 int upper = s[o] - 'A';
  62.                 printf("%c", toupper(key[upper]));
  63.             }
  64.             else if (isalpha(s[o]) && islower(s[o]))
  65.             {
  66.                 int lower = s[o] - 'a';
  67.                 printf("%c", tolower(key[lower]));
  68.             }
  69.             else
  70.             {
  71.                 printf("%c", s[o]);
  72.             }
  73.         }
  74.         printf("\n");
  75.         return 0;
  76.  
  77.     }
  78.  
  79.     // User inputs more than a single key
  80.     if (argc != 2 || isdigit(argv[1]))
  81.     {
  82.         printf("Usage: ./substitution key\n");
  83.         return 1;
  84.     }
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement