Skip to content

Instantly share code, notes, and snippets.

@ThatOneCubanDude
Created March 26, 2020 22:56
Show Gist options
  • Save ThatOneCubanDude/b55d391dd3ef9c2475fdc63b71b2ba3a to your computer and use it in GitHub Desktop.
Save ThatOneCubanDude/b55d391dd3ef9c2475fdc63b71b2ba3a to your computer and use it in GitHub Desktop.
My solution to CS50x Problem Set 2 - Caesar. Feel free to critique or ask questions.
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
int main(int argc, string argv[])
{
//checks if user input exactly 1 command line argument, if not prints out error message
if (argc == 2)
{
//checks if argument is a number, if not prints out error message
for (int i = 0, n = strlen(argv[1]); i < n; i++)
{
if (isdigit(argv[1][i]) == 0)
{
printf("Usage: ./caesar key\n");
return 1;
}
}
}
else
{
printf("Usage: ./caesar key\n");
return 1;
}
//gets the text the user wants to encode and stores it as plaintext
string plaintext = get_string("plaintext: ");
//stores the command line argument inputed earlier to use as key for encryption
int key = atoi(argv[1]);
for (int i = 0, n = strlen(plaintext); i < n; i++)
{
//creates variable "bound_check" to later check whether the program should wrap from z or not
int bound_check = (plaintext[i] + key);
//makes sure the program will only change letters
if (isalpha(plaintext[i]) != 0)
{
//seperate algorithm for uppercase letters ie: "A,B,C..."
if (isupper(plaintext[i]) != 0)
{
//if there is no need to wrap back to A, simply add key to character in "i" position in "plaintext"
if (bound_check >= 65 && bound_check < 90)
{
plaintext[i] = (plaintext[i] + key);
}
//if there is a need to wrap back to A, add key to character in "i" position in "plaintext" and then wrap to A
else if (bound_check > 90)
{
plaintext[i] = ((((plaintext[i] + key) - 65) % 26) + 65);
}
}
//seperate algorithm for lowercase letters ie: "a,b,c..."
else if (islower(plaintext[i]) != 0)
{
//if there is no need to wrap back to a, simply add key to character in "i" position in "plaintext"
if (bound_check >= 97 && bound_check < 122)
{
plaintext[i] = (plaintext[i] + key);
}
//if there is a need to wrap back to a, add key to character in "i" position in "plaintext" and then wrap to a
else if (bound_check > 122)
{
plaintext[i] = ((((plaintext[i] + key) - 97) % 26) + 97);
}
}
}
}
//outputs the encoded text
printf("ciphertext: %s\n", plaintext);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment