LeonardoGraham

Untitled

Oct 21st, 2020
1,172
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <ctype.h>
  4.  
  5. int main(void) {
  6.     //  Variable Declaration
  7.     const int SIZE_OF_STRING = 50;
  8.     const int SIZE_OF_KEY = 25;
  9.     const int NUM_ALPHABET = 26;
  10.     char plaintext[SIZE_OF_STRING];
  11.     char ciphertext;
  12.     char keyString[SIZE_OF_KEY];
  13.     int key;
  14.  
  15.     //  Gather phrase and key
  16.     printf("plaintext: ");
  17.     fgets(plaintext, SIZE_OF_STRING, stdin);
  18.     printf("key: ");
  19.     fgets(keyString, SIZE_OF_KEY, stdin);
  20.     //  Store length of strings
  21.     int plainLen = strlen(plaintext) - 1;
  22.     int keyLen = strlen(keyString) - 1;
  23.     //  Makes sure key is undercase
  24.     for (int i = 0; i < keyLen; i++) {
  25.         if (isalpha(keyString[i]) == 0) {  
  26.             printf("Key contains non-alphabetic values.\nExiting Program!\n");
  27.             return 1;
  28.         }
  29.     }
  30.     // Print "ciphertext"
  31.     printf("ciphertext: ");
  32.     // Access characters in plaintext and manages key
  33.     for (int i = 0, j = 0; i < plainLen; i++, j %= keyLen)
  34.     {
  35.         // Converts string to integer and creates key
  36.         key = (isupper(keyString[j] != 0)) ? keyString[j] - 'A' : keyString[j] - 'a';
  37.         // Handles uppercase letters
  38.         if (isupper(plaintext[i]))
  39.         {
  40.             ciphertext = (plaintext[i] - 'A' + key) % NUM_ALPHABET + 'A';
  41.             printf("%c", ciphertext);
  42.             j++;
  43.         }
  44.         // Handles lowercase letters
  45.         else if (islower(plaintext[i]))
  46.         {
  47.             ciphertext = (plaintext[i] - 'a' + key) % NUM_ALPHABET + 'a';
  48.             printf("%c", ciphertext);
  49.             j++;
  50.         }
  51.         // Handles the rest
  52.         else
  53.         {
  54.             ciphertext = plaintext[i];
  55.             printf("%c", ciphertext);
  56.         }
  57.     }
  58.     // Next line
  59.     printf("\n");
  60. }
RAW Paste Data