Advertisement
daniel_lawson9999

Daniel Lawson Caesar Cipher

Oct 4th, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.07 KB | None | 0 0
  1. #include <cs50.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. //Daniel Lawson
  6. void getCipher(string text, int shift);
  7.  
  8. int main(int argc, string argv[])
  9. {
  10.     if (argc != 2) //make sure only 2 arguments are entered
  11.     {
  12.         printf("Please only print one addtional argument (./caesar 14)\n");
  13.         return 1;
  14.     }
  15.  
  16.     int shift = atoi(argv[1]); //get the "shift" value
  17.     printf("plaintext: ");//ask for plaintext
  18.     string text = get_string();//store it
  19.  
  20.     getCipher(text, shift);//call the cipher method, which converts text into ciphertext
  21.  
  22.     printf("ciphertext: %s\n", text); //print the cipher
  23.  
  24.     return 0;
  25. }
  26.  
  27. //I made a method b/c to have for the next problem, so I can just copy and paste
  28. void getCipher(string text, int shift)
  29. {
  30.     int length = strlen(text); //store the length of the string
  31.     for (int i = 0; i < length; i++)//iterate over each character
  32.     {
  33.         if (text[i] != ' ') //don't do anything if the current character is a char
  34.         {
  35.             int originalChar = (int) text[i]; //get the char, and conver to decimal
  36.             int fromZero; //will store the from 0 value of the char
  37.             int caseValue = 0; //will store the decimal value for if the character is capital or not
  38.             if (originalChar >= 97)
  39.             {
  40.                 caseValue = 97;
  41.             }
  42.             else if (originalChar >= 65)
  43.             {
  44.                 caseValue =  65;
  45.             }
  46.             fromZero = originalChar - caseValue; //make fromZero equal to the original minus the case value
  47.             fromZero = (fromZero + shift) % 26; //add shift to fromZero, then % 26
  48.             text[i] = (char) caseValue +
  49.                       fromZero; //add fromZero to caseValue and return to char, and replace the former value of text
  50.         }
  51.     }
  52. }
  53.  
  54.  
  55.  
  56.  
  57. //A starts at 65, a starts at 97
  58. /* sample output
  59.  
  60. ~/workspace/pset2 $ ./caesar 13
  61. Be sure to drink your Ovaltine!
  62. Or fher gb qevax lbhe Binygvar!
  63. */
  64.  
  65. /*io
  66. plaintext:
  67. ciphertext:
  68. */
  69.  
  70. /*sample potato algorithm
  71. ci = (pi + k) % 26
  72. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement