Skip to content

Instantly share code, notes, and snippets.

@Catsquotl
Created May 31, 2019 07:56
Show Gist options
  • Save Catsquotl/80aff0b2e06ba566f60e8161a79d6cdc to your computer and use it in GitHub Desktop.
Save Catsquotl/80aff0b2e06ba566f60e8161a79d6cdc to your computer and use it in GitHub Desktop.
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(int argc, string argv[])
{
string cipher_key;
//check to see if argv has only one argument. [0] == prog-name hence the <=2
//if it does assign it to var.
if (argc == 2)
{
cipher_key = argv[1];
}
//check to see if arg is valid(0-9) if so do nothing, else print usage and exit.
for (int i = 0; i < strlen(cipher_key); i++)
{
if (cipher_key[i] > 47 && cipher_key[i] < 58)
{
}
else
{
printf("Usage: ./caesar key\n");
return 1;
}
}
//if we didn't exit, print succes and ask for message.
printf("success = %s\n", cipher_key);
string plain = get_string("plaintext: ");
string ciphered = plain;
// the conversion. check if char is a valid letter (lower or uppercase) then change it.
int upper[] = {64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90};
int lower[] = {97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122};
for (int i = 0; i < strlen(ciphered); i++)
{
if ((int)ciphered[i] > 64 && (int)ciphered[i] < 91)
{
ciphered[i] = upper[((ciphered[i] + atoi(cipher_key) - 64) % 26)];
}
else if ((int)ciphered[i] > 96 && (int)ciphered[i] < 123)
{
ciphered[i] = lower[((ciphered[i] + atoi(cipher_key) - 97) % 26)];
}
}
//print encoded message
printf("ciphertext: %s\n", ciphered);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment