Skip to content

Instantly share code, notes, and snippets.

@sameekapdi
Created November 8, 2017 12:39
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 sameekapdi/c676f37bfb02a704d2432e02312e4b1b to your computer and use it in GitHub Desktop.
Save sameekapdi/c676f37bfb02a704d2432e02312e4b1b to your computer and use it in GitHub Desktop.
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, string argv[])
{
//CHeck to see if the correct number of arguments have been entered.
if (argc != 2)
{
printf("Please enter the correct number of arguments\n");
return 1;
}
else
{
for (int i = 0, n = strlen(argv[1]); i<n; i++)
{
if(!isalpha(argv[1][i]))
{
printf("Please enter the correct argument. Key must be alphabetic characters only.");
return 1;
}
}
}
//Get key from argument as a string and get the length
string key = argv[1];
int key_length = strlen(key);
//Get user input for plaintext
printf("plaintext: ");
string plaintext = get_string();
if (plaintext != NULL)
{
printf("ciphertext: ");
//Iterate through the string and convert each letter
for (int i = 0, j = 0, n = strlen(plaintext); i < n; i++)
{
//Get the key for this letter
int letter_key = tolower(key[j % key_length])-97;
//Check for lowercase
if (islower(plaintext[i]))
{
printf("%c", ((((plaintext[i] - 97) + letter_key) % 26) + 97));
j++;
}
//check for uppercase
else if(isupper(plaintext[i]))
{
printf("%c", ((((plaintext[i] - 65) + letter_key) % 26) + 65));
j++;
}
//Print non-alpha characters as they are
else
{
printf("%c", plaintext[i]);
}
}
}
//Print new line to end the deciphered text.
printf("\n");
//Exit the program
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment