Advertisement
kevinml

vigenere.c

Oct 15th, 2014
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.52 KB | None | 0 0
  1. #include <ctype.h>
  2. #include <cs50.h>
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include <stdlib.h>
  6. #include <math.h>
  7.  
  8. int main(int argc, string argv[])
  9. {
  10.     // ensure that user input a key
  11.     if (argc > 1 && argc < 3)
  12.     {
  13.         int s = strlen(argv[1]);
  14.         // create array for string
  15.         int key[s];
  16.         // get plaintext string from user
  17.         string m = GetString();
  18.         // do for the length of plaintext string
  19.         for (int j = 0, i = 0, num = strlen(m); j <= num; j++, i++)
  20.         {
  21.             // check case and validitiy of char in array
  22.             if (islower(argv[1][j]))
  23.             {
  24.                 // assign jth char of key to jth char of argv
  25.                 key[j] = (argv[1][j] - 97);
  26.                 // check message case for ith char
  27.                 if((m[i] >= 'A') && (m[i] <= 'Z'))
  28.                 {
  29.                     m[i] = ((m[i] -'A') + key[j % strlen(argv[1])]) % 26 +'A';
  30.                     printf("%c", m[i]);
  31.                 }
  32.  
  33.                 if((m[i] >= 'a') && (m[i] <= 'z'))
  34.                 {
  35.                     m[i] = ((m[i] -'a') + key[j % strlen(argv[1])]) % 26 +'a';
  36.                     printf("%c", m[i]);
  37.                 }
  38.             }
  39.             else if (isupper(argv[1][j]))
  40.             {
  41.                 key[j] = (argv[1][j] - 65);
  42.                 if((m[i] >= 'A') && (m[i] <= 'Z'))
  43.                 {
  44.                     m[i] = ((m[i] -'A') + key[j % strlen(argv[1])]) % 26 +'A';
  45.                     printf("%c", m[i]);
  46.                 }
  47.  
  48.                 if((m[i] >= 'a') && (m[i] <= 'z'))
  49.                 {
  50.                     m[i] = ((m[i] -'a') + key[j % strlen(argv[1])]) % 26 +'a';
  51.                     printf("%c", m[i]);
  52.                 }
  53.  
  54.             }  
  55.         }
  56.         printf("\n");
  57.         return 0;  
  58.        
  59.      }
  60.      else
  61.         printf("You must enter a key!\n");
  62.         return 1;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement