Advertisement
Eastkap

cs50's caesar.c

Aug 5th, 2014
241
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.48 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <cs50.h>
  3. #include <stdlib.h>
  4. #include <ctype.h>
  5. #include <string.h>
  6.  
  7. int main (int argc, string argv[]){
  8.     // testing if user has put correct number of arguments in command-line
  9.     if (argc != 2){
  10.         return 1;
  11.     }
  12.    
  13.     // transforming the string containing the key into an actual integer
  14.     int k = atoi(argv[1]);
  15.    
  16.     //getting the plain text from the user
  17.     string  plaintext = GetString();
  18.    
  19.     //declaring the string that will contain the cypher text
  20.     string cipher[strlen(plaintext)];
  21.    
  22.     int letter;
  23.    
  24.     for (int i=0, j= strlen(plaintext); i<j; i++)
  25.     {
  26.        // getting letter to be changed
  27.        letter = (int) plaintext[i];
  28.        // checking if character is actually alphabetic
  29.        if (isalpha(plaintext[i])){
  30.              
  31.            letter = (letter) + (k% 26);
  32.            // checking if wrap round  from Z to A is needed
  33.            if (isupper(plaintext[i])){
  34.                if (letter>90){
  35.                    letter= 65+ letter-91;
  36.                }
  37.            }
  38.            if (islower(plaintext[i])){
  39.            // checking if wrap round  from z to a is needed
  40.                if (letter>122){
  41.                    letter= 97+ letter-123;
  42.                }
  43.            }
  44.            cipher[i]= (string) letter;
  45.            printf("%c", (char) cipher[i]);
  46.        }
  47.        else{
  48.            printf("%c", (plaintext[i]));
  49.        }
  50.        
  51.     }
  52.     printf("\n");
  53.     return 0;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement