Advertisement
decs4usa

vigenere

Nov 10th, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.15 KB | None | 0 0
  1. #include <cs50.h>
  2. #include <stdio.h>
  3. #include <ctype.h>
  4. #include <string.h>
  5. #include <stdlib.h>
  6.  
  7. int shift(char key);
  8.  
  9. int main(int argc, string argv[])
  10.  
  11. {
  12.     if (argc != 2) //if user doesn't run command-line argument of one or enter positive int  
  13.     {
  14.         printf("Usage: ./vigenere key\n"); //prompt them to run it again
  15.         return 1; //returning zero means everything went well
  16.     }
  17.    
  18.     for (int j = 0, n = strlen(argv[1]);  j < n; j++)  //length of the entire string. Save n as strlen for use in loop
  19.     {
  20.         if (isalpha(argv[1][j])) //if user doesn't run command-line argument of one or enter positive int and user inputs an alpha key, continue
  21.  
  22.         {
  23.             //printf("%c\n", argv[1][j]); //Print after collecting plaintext
  24.         }
  25.  
  26.    
  27.         else
  28.  
  29.         {      
  30.             printf("Usage: ./vigenere key\n"); //prompt them to run it again
  31.             return 1; //returning zero means everything went well
  32.         }
  33.  
  34.     }  
  35.    
  36.     string p = get_string("plaintext: "); //prompt for plaintext and store
  37.     string key = argv[1]; //declare the key as a string
  38.     char cipher; //declare cipher as a char
  39.        
  40.     //NOW ROTATE BY THE KEY
  41.    
  42.     for (int i = 0; i < strlen(p); i++) //length of the entire string
  43.     {  
  44.        
  45.         if (isupper(p[i]))
  46.                
  47.         {
  48.             cipher = (((p[i] + shift(key[j])) - 65) % 26) + 65; //Use the new shift function now
  49.             printf("ciphertext: %c", cipher); //print ciphertext after rotating
  50.         }
  51.    
  52.         else if (islower(p[i]))
  53.                
  54.         {
  55.             cipher = (((p[i] + shift(key[j])) - 97) % 26) + 97; //add key and rotate
  56.             printf("ciphertext: %c", cipher); //print ciphertext after rotating
  57.         }
  58.              
  59.         else
  60.            
  61.         {
  62.             printf("ciphertext: %c", p[i]);
  63.         }
  64.                
  65.     }
  66.     printf("\n");
  67.     return 0;    
  68.    
  69.    
  70. } //Closing braces
  71.  
  72.  
  73.  
  74. //function definition
  75. int shift(char c); //NEW SHIFT function
  76. {
  77.     int k;
  78.  
  79.     if (islower(c))
  80.         {
  81.             k = c - 97;
  82.         }
  83.    
  84.     if (isupper(c))
  85.         {
  86.             k = c - 65;
  87.         }
  88.    
  89.     return k;
  90.                
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement