Created
May 19, 2020 22:30
-
-
Save araidz/2b36561bc1e2520015f3f6b442d25c80 to your computer and use it in GitHub Desktop.
CS50 Pset2 Substitution
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
/* | |
CS50 Substitution | |
araidz | |
*/ | |
#include <cs50.h> | |
#include <ctype.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
int main(int argc, string argv[]) | |
{ | |
// Declare the variables | |
int key_len, text_len, i, j; | |
string plain_text, key; | |
if (argc != 2) | |
{ | |
printf("Usage: ./substitution key\n"); | |
return 1; | |
} | |
// Assign the key to variable key | |
key = argv[1]; | |
// Get the length of the key | |
key_len = strlen(argv[1]); | |
if (key_len != 26) | |
{ | |
// Check if key is 26 letters | |
printf("Key must contain 26 characters.\n"); | |
return 1; | |
} | |
else | |
{ | |
for (i = 0; i < key_len; i++) | |
{ | |
// Check if char is not a letter | |
if (!isalpha(key[i])) | |
{ | |
printf("Key must contain 26 characters.\n"); | |
return 1; | |
} | |
for (j = i + 1; j < key_len; j++) | |
{ | |
// Check if char is not a duplicate | |
if (key[i] == key[j]) | |
{ | |
printf("Key must contain 26 characters.\n"); | |
return 1; | |
} | |
} | |
} | |
// Get user input for plaintext | |
plain_text = get_string("plaintext: "); | |
// Get the length of the plaintext | |
text_len = strlen(plain_text); | |
printf("ciphertext: "); | |
// Store ciphertext in a variable | |
char cipher_text[text_len]; | |
// Iterate through each char in the plaintext | |
for (i = 0; i < text_len; i++) | |
{ | |
// Check if char is a letter | |
if (isalpha(plain_text[i])) | |
{ | |
// Check if letter is upeer | |
if (isupper(plain_text[i])) | |
{ | |
cipher_text[i] = toupper(key[plain_text[i] - 65]); | |
} | |
// Check if letter is lower | |
else if (islower(plain_text[i])) | |
{ | |
cipher_text[i] = tolower(key[plain_text[i] - 97]); | |
} | |
} | |
// Check if char is not a letter | |
else | |
{ | |
cipher_text[i] = plain_text[i]; | |
} | |
} | |
// Print a new line after ciphertext | |
printf("%s\n", cipher_text); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment