-
-
Save sameekapdi/c676f37bfb02a704d2432e02312e4b1b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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