#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <ctype.h> | |
#include <cs50.h> | |
#define UPPER_ALPHA_INDEX 65 | |
#define LOWER_ALPHA_INDEX 97 | |
#define ALPHABET_MAX 26 | |
char encipher(char index, int cipher_key); | |
int convert_key(char index); | |
int main(int argc, string argv[]) | |
{ | |
// Get the key from the user | |
string cipher_key; | |
// Guard against the user not entering the correct number of command line arguments | |
if(argc != 2) | |
{ | |
printf("Error: Incorrect number of arguments passed!\n"); | |
return 1; | |
} | |
for(int i = 0; i < strlen(argv[1]); i++) | |
{ | |
if ( isupper(argv[1][i]) || islower(argv[1][i]) ) | |
continue; | |
else | |
{ | |
printf("Error: Something in the cipher_key was not a valid character\n"); | |
return 1; | |
} | |
} | |
cipher_key = argv[1]; | |
// Get the plain text they want to encode | |
string cipher_text = ""; | |
do | |
{ | |
printf("\nNOTE: Only uppercase and lowercase letters will be encoded\n"); | |
cipher_text = get_string("Please enter the text to encode to continue: "); | |
} | |
while(strlen(cipher_text) == 0); | |
// Encipher | |
printf("ciphertext: "); | |
int key_len = strlen(cipher_key); | |
int converted_key; | |
for (int i = 0, j = 0; i < strlen(cipher_text); i++) | |
{ | |
if(isupper(cipher_text[i]) || islower(cipher_text[i])) | |
{ | |
converted_key = convert_key( cipher_key[j % key_len]); | |
j++; | |
} | |
else | |
{ | |
converted_key = 0; | |
} | |
printf("%c", encipher(cipher_text[i], converted_key) ); | |
} | |
printf("\n"); | |
} | |
// The way to encipher is by understanding the ascii indicies for each letter. | |
// Because lowercase letters and uppercase letters have arbitrary indicies | |
// we must first adjust the indicies so 'a' and 'A' start at index 0 | |
// This is done by subtracting either UPPER_ALPHA_INDEX or LOWER_ALPHA_INDEX | |
// once the index is in the correct mapping we can add or subtract the cipher key | |
// and use the modulo operator to get the new index | |
// finally we re-adjust back up to the ascii index | |
// by adding back UPPER_ALPHA_INDEX or LOWER_ALPHA_INDEX | |
// Anything that isn't a character is returned back to the caller | |
char encipher(char index, int cipher_key) | |
{ | |
if ( isupper(index) ) | |
{ | |
index -= UPPER_ALPHA_INDEX; | |
index += cipher_key; | |
index %= ALPHABET_MAX; | |
index += UPPER_ALPHA_INDEX; | |
return index; | |
} | |
else if ( islower(index) ) | |
{ | |
index -= LOWER_ALPHA_INDEX; | |
index += cipher_key; | |
index %= ALPHABET_MAX; | |
index += LOWER_ALPHA_INDEX; | |
return index; | |
} | |
else | |
return index; | |
} | |
int convert_key(char index) | |
{ | |
if ( isupper(index) ) | |
return index - UPPER_ALPHA_INDEX; | |
else if ( islower(index) ) | |
return index - LOWER_ALPHA_INDEX; | |
else | |
return 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment