Advertisement
RaphaelMiedl

CS50 caesar cypher

Jun 4th, 2014
359
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.93 KB | None | 0 0
  1. //caesar_character is a function that takes a single character and the key to use for the cypher and returns the encoded character back.
  2.  
  3. #include <cs50.h>
  4. #include <ctype.h>
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8.  
  9. char caesar_character(char ch, int key);
  10.  
  11. int main(int argc, string argv[])
  12. {
  13.     if (argc != 2)
  14.     {
  15.         printf("You must suply exactly one argument!\n");
  16.         return 1;
  17.     }
  18.    
  19.     int key = atoi(argv[1]);
  20.     string original = GetString();
  21.    
  22.     for (int i = 0, len = strlen(original); i < len; ++i)
  23.     {
  24.         printf("%c", caesar_character(original[i], key));
  25.     }
  26.    
  27.     printf("\n");
  28.    
  29.     return 0;
  30. }
  31.  
  32. char caesar_character(char ch, int key)
  33. {
  34.     if (islower(ch))
  35.     {
  36.         return (ch - 'a' + key) % 26 + 'a';
  37.     }
  38.     else if (isupper(ch))
  39.     {
  40.         return (ch - 'A' + key) % 26 + 'A';
  41.     }
  42.     else
  43.     {
  44.         return ch;
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement