Advertisement
Guest User

Untitled

a guest
Jul 16th, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.36 KB | None | 0 0
  1. #include <cs50.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <ctype.h>
  6.  
  7. int shift(char c);
  8. char cipher(int x, char y);
  9.  
  10. int main(int argc, string argv[])
  11. {
  12.  
  13.   //save argv 1 to key
  14.   string key = argv[1];
  15.   string text;
  16.  
  17.   //rest of the code only executes if user enters a word without any numbers
  18.   if (argc != 2) {
  19.     printf("Usage: ./vigenere keyword\n");
  20.     return 1;
  21.   } else {
  22.     for (int i = 0, j = strlen(key); i < j; i++) {
  23.       if (!isalpha(key[i])) {
  24.         printf("Usage: ./vigenere keyword\n");
  25.       }
  26.        
  27.     }
  28.       text = get_string("plaintext: ");
  29.   }
  30.    
  31.     printf("ciphertext: ");
  32.    
  33.     for (int i = 0, j = strlen(text); i < j; i++) {
  34.         if(isspace(text[i])) {
  35.             printf(" ");
  36.         }else{
  37.             for (int a = 0, b = strlen(key); a < b; a++) {
  38.                 if (a == b) {
  39.                     a = 0;
  40.                 }
  41.                
  42.                printf("%c", cipher(shift(key[a]),text[i]));
  43.             }
  44.         }
  45.     }
  46.    
  47. }
  48.  
  49. int shift(char c) {
  50.   int shift = c;
  51.   if (shift >= 65 && shift <= 90) {
  52.     shift -= 65;
  53.   } else {
  54.     shift -= 97;
  55.   }
  56.   return shift;
  57. }
  58.  
  59. char cipher(int x, char y) {
  60.   int pc = y;
  61.  
  62.   if (islower(y)) {
  63.     return ((((pc + x) - 97) % 26) + 97);
  64.   } else {
  65.     return ((((pc + x) - 65) % 26) + 65);
  66.   }
  67.  
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement