Last active
June 11, 2020 15:44
-
-
Save kinoute/1bdfc0baa5d937ea5421713a0c165e44 to your computer and use it in GitHub Desktop.
Harvard CS50 substitution
This file contains hidden or 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 <stdio.h> | |
#include <string.h> | |
#include <ctype.h> | |
int main(int argc, string argv[]) | |
{ | |
// the user must provide one and only argument | |
if (argc != 2) | |
{ | |
printf("Your forgot the key, duh.\n"); | |
return 1; | |
} | |
// we only accept a key of size 26 | |
else if (strlen(argv[1]) != 26) | |
{ | |
printf("You must provide a key with a length of 26 characters.\n"); | |
return 1; | |
} | |
else | |
{ | |
for (int i = 0, n = strlen(argv[1]); i < n; i++) | |
{ | |
// check if the key is all about alphabetic | |
if (!isalpha(argv[1][i])) | |
{ | |
printf("The key should only contain alpha characters.\n"); | |
return 1; | |
} | |
// check if every character is only used once | |
for (int j = i + 1; j < n; j++) | |
{ | |
if (argv[1][i] == argv[1][j]) | |
{ | |
printf("A key cannot have a same character more than once!\n"); | |
return 1; | |
} | |
} | |
} | |
} | |
// store the key argument | |
string key = argv[1]; | |
// get the text to encrypt | |
string plaintext = get_string("plaintext: "); | |
// prepare the encrypted variable | |
char ciphertext[strlen(plaintext)]; | |
for (int i = 0, n = strlen(plaintext); i < n; i++) | |
{ | |
// if the character is upper of lower, the alphabet start is not the same | |
int alpha_index = plaintext[i] - ((isupper(plaintext[i])) ? 65 : 97); | |
// do nothing if the given character is not alphabetic | |
if (!isalpha(plaintext[i])) | |
{ | |
ciphertext[i] = plaintext[i]; | |
} | |
else // respect the lower or uppercase of the plaintext character | |
{ | |
ciphertext[i] = islower(plaintext[i]) ? tolower(key[alpha_index]) : key[alpha_index]; | |
} | |
} | |
// show result | |
printf("ciphertext: %s\n", ciphertext); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nul ce code