Last active
May 7, 2016 01:09
-
-
Save rberaldo/6c292de4b3984441269b3580173f5b54 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* caesar.c | |
* | |
* Rafael Beraldo | |
* rberaldo@cabaladada.org | |
* | |
* Encrypts text with the Caesar cipher | |
*/ | |
#include <stdio.h> | |
#include <cs50.h> | |
#include <stdlib.h> | |
#include <ctype.h> | |
#include <string.h> | |
/* In order for the encryption function to work, we must first get the | |
alphabetical index of a character by subtracting 65 if it is uppercase and 97 | |
if it is lowercase. That's because in ASCII, they are not 0-indexed. */ | |
#define UPPERCASE_ASCII_SHIFT 65 | |
#define LOWERCASE_ASCII_SHIFT 97 | |
#define SIZE_ALPHABET 26 | |
// Functions | |
char encrypt(char letter, int key, int shift); | |
int main(int argc, string argv[]) | |
{ | |
// Exits if program has less or more than one argument | |
if (argc != 2) | |
{ | |
printf("Usage: %s <key>\n", argv[0]); | |
return 1; | |
} | |
int key = atoi(argv[1]); | |
string message = GetString(); | |
// Cycle though all characters in message | |
for (int i = 0, message_length = strlen(message); i < message_length; i++) | |
{ | |
if (!isalpha(message[i])) | |
{ | |
printf("%c", message[i]); | |
} | |
else if (isupper(message[i])) | |
{ | |
printf("%c", encrypt(message[i], key, UPPERCASE_ASCII_SHIFT)); | |
} | |
else | |
{ | |
printf("%c", encrypt(message[i], key, LOWERCASE_ASCII_SHIFT)); | |
} | |
} | |
printf("\n"); | |
return 0; | |
} | |
///////////////////////////////////////////// | |
/** | |
* Encrypts a character using a key, shifting to correct for the ASCII table | |
*/ | |
char encrypt(char letter, int key, int shift) | |
{ | |
letter -= shift; | |
return (letter + key) % SIZE_ALPHABET + shift; | |
} |
@mike168m isalpha()
is part of the ctype.h
library and returns true
if a character is an alphabetic letter. I found it here: https://reference.cs50.net/ctype.h/isalpha
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
what does isAlpha() do?