Skip to content

Instantly share code, notes, and snippets.

@voidnerd
Last active April 19, 2020 21:05
Show Gist options
  • Save voidnerd/a46de594597f9a0b1a0fd8c090eeddac to your computer and use it in GitHub Desktop.
Save voidnerd/a46de594597f9a0b1a0fd8c090eeddac to your computer and use it in GitHub Desktop.
CS50's Problem Set 2 - Caesar Cipher
#include <stdio.h>
#include <ctype.h>
#include <cs50.h>
#include <string.h>
#include <stdlib.h>
bool isNumber(char number[]);
int main(int argc, string argv[])
{
if (argc != 2 || !isNumber(argv[1]))
{
printf("Usage: ./caesar key\n");
return 1;
}
else
{
int k = atoi(argv[1]);
printf("%i", k);
string plaintext = get_string("Plaintext: ");
printf("ciphertext: ");
for (int i = 0, len = strlen(plaintext); i < len; i++)
{
if (isalpha(plaintext[i]))
{
if (isupper(plaintext[i]))
{
printf("%c", (((plaintext[i] - 65) + k) % 26) + 65);
}
else
{
printf("%c", (((plaintext[i] - 97) + k) % 26) + 97);
}
}
else
{
printf("%c", plaintext[i]);
}
}
printf("\n");
return 0;
}
}
bool isNumber(char number[])
{
int i = 0;
if (number[0] == '-')
i = 1;
for (; number[i] != 0; i++)
{
if (!isdigit(number[i]))
return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment