Skip to content

Instantly share code, notes, and snippets.

@edieblu
Created April 28, 2021 16:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edieblu/efcbb9275b838d3730f496e8baf8a74f to your computer and use it in GitHub Desktop.
Save edieblu/efcbb9275b838d3730f496e8baf8a74f to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <cs50.h>
// plaintext (p) vs ciphertex (c), and a key (k)
// “rotate” each (alphabetical) character by k positions
// Your program must accept a single command-line argument, a non-negative integer
// Your program must preserve case
// lowercase: 65(a) - 90(z)
// uppercase: 97(a) - 122(z)
// isalpha, islower, isupper, isdigit
int main(int argc, string argv[])
{
if (argc == 2)
{
for (int i = 0; i < strlen(argv[1]); i++)
{
if (isdigit(argv[1][i]) == 0)
{
printf("Usage: ./caesar k\n");
return 1;
}
}
int k = atoi(argv[1]);
string p = get_string("plaintext: ");
printf("ciphertext: ");
for (int i = 0, len = strlen(p); i < len; i++)
{
if (islower(p[i]))
{
printf("%c", (((p[i] - 'a') + k) % 26) + 'a');
}
else if (isupper(p[i]))
{
printf("%c", (((p[i] - 'A') + k) % 26) + 'A');
}
else
{
printf("%c", p[i]);
}
}
printf("\n");
return 0;
}
else
{
printf("Usage: ./caesar k\n");
return 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment