Advertisement
Guest User

Untitled

a guest
Jul 17th, 2018
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.83 KB | None | 0 0
  1. #include <cs50.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <stdlib.h>
  5. #include <ctype.h>
  6.  
  7. int main(int argc, string argv[])
  8. {
  9.     //Check correct # of characters
  10.     if (argc != 2)
  11.     {
  12.         printf("Error!\n");
  13.         return 1;
  14.     }
  15.     //reject if there are non-alphabet characters in keyword
  16.     for (int i = 0; i < strlen(argv[1]); i++)
  17.     {
  18.         if (!isalpha(argv[1][i]))
  19.         {
  20.             printf("Error!\n");
  21.             return 1;
  22.         }
  23.     }
  24.  
  25.     int keylength = strlen(argv[1]);
  26.     if (argc == 2)
  27.     {
  28.         //get the plaintext
  29.         string plain = get_string("plaintext: ");
  30.         int plainlength = strlen(plain);
  31.         printf("ciphertext: ");
  32.         //for each character in the plaintext
  33.         for (int i = 0, s = 0; i < plainlength; i++)
  34.         {
  35.             //if it's an alphabet
  36.             if (isalpha(plain[i]))
  37.             {
  38.                 int key = (tolower(argv[1][s % keylength])) - 97;// key
  39.                 //if it's lowercase
  40.                 if (islower(plain[i]))
  41.                 {
  42.                     int lowercipher = (((plain[i] + key) - 97) % 26) + 97;
  43.                     printf("%c", lowercipher);
  44.                     s++;
  45.                 }
  46.                 // if it's uppercase, do same thing as lowercase but change to uppercase in the end
  47.                 if (isupper(plain[i]))
  48.                 {
  49.                     int uppercipher = (((tolower(plain[i]) + key) - 97) % 26) + 97;
  50.                     printf("%c", toupper(uppercipher));
  51.                     s++;
  52.                 }
  53.             }
  54.             //if it's any other character, print that character
  55.             else
  56.             {
  57.                 printf("%c", plain[i]);
  58.             }
  59.         }
  60.         //line break after plaintext is converted to ciphertext
  61.         printf("\n");
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement