Advertisement
Guest User

Untitled

a guest
Oct 12th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.76 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <cs50.h>
  3. #include <stdlib.h>
  4. #include <ctype.h>
  5. #include <string.h>
  6. #include <math.h>
  7.  
  8. //Get the key right from the command line argument
  9. int main(int argc, string argv[])
  10. {
  11.     //if the key has more or less than a single character and if the keyword is not alphabetical, end the program
  12.     if (argc != 2)
  13.     {
  14.         printf("You must enter a single string as the key\n");
  15.         return 1;
  16.     }
  17.     for (int k = 0, n = strlen(argv[1]); k < n; k++)
  18.     {
  19.         while (!isalpha(argv[1][k]))
  20.         {
  21.             printf("The key must be alphabetical\n");
  22.             return 1;
  23.         }
  24.     }
  25.  
  26.     //Prompt the user for the plaintext
  27.     string plaintext = get_string("Write a text to encrypt: ");
  28.  
  29.     string keyword = argv[1];
  30.  
  31.     int s = strlen(plaintext);
  32.  
  33.     //Print the response previous to the ciphering
  34.     printf("ciphertext: ");
  35.  
  36.     //iterate over every plaintext and keyword character
  37.     for (int i = 0, j = 0, n = strlen(keyword); i < s; i++)
  38.     {
  39.  
  40.         //check if the plaintext character is alphabetic
  41.         if (isalpha(plaintext[i]))
  42.         {
  43.             //Preserve upper cases and lower cases of each character
  44.             if (isupper(plaintext[i]))
  45.             {
  46.                 printf("%c", ((plaintext[i] - 65 + keyword[j] - 65) % 26 + 65));
  47.                 j = (j + 1) % n;
  48.             }
  49.  
  50.             if (islower(plaintext[i]))
  51.             {
  52.                 printf("%c", ((plaintext[i] - 97 + keyword[j] - 97) % 26 + 97));
  53.                 j = (j + 1) % n;
  54.             }
  55.         }
  56.  
  57.         //Print the non-alphabetic characters without applying the keyword
  58.         else
  59.         {
  60.             printf("%c", plaintext[i]);
  61.         }
  62.  
  63.     }
  64.  
  65.     printf("\n");
  66.     return 0;
  67.  
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement