Skip to content

Instantly share code, notes, and snippets.

@Juskr04
Last active July 17, 2025 11:33
Show Gist options
  • Select an option

  • Save Juskr04/44b7f233c498e32268acbe8f7aed6736 to your computer and use it in GitHub Desktop.

Select an option

Save Juskr04/44b7f233c498e32268acbe8f7aed6736 to your computer and use it in GitHub Desktop.
cs50 pset2 substitution problem
#include<stdio.h>
#include"functions.c"
int check_key_validity(char argv[]); // checks whether the key given by the user is valid or not according to constraints
int main(int argc, char* argv[]){
if(argc != 2){
printf("Usage : ./program_name key");
return 1;
}
int key_validity = check_key_validity(argv[1]);
if(key_validity != 0){
printf("INVALID KEY\n");
return 1;
}
char plaintext[1000];
char ciphertext[1000];
printf("plaintext: ");
fgets(plaintext, sizeof(plaintext), stdin);
//encrypting with user key
int i = 0;
while(plaintext[i] != '\0'){
if(is_alphabet_char(plaintext[i]) == 1){
ciphertext[i] = plaintext[i];
i++;
continue;
}
int plaintext_casecheck = alphabet_case_check(plaintext[i]);
if(plaintext_casecheck == 0)
ciphertext[i] = argv[1][(int)(plaintext[i] - 'a')]; // same concept as repeat letter function have to cast (plaintext[i] - 'A') to int because difference of 2 characters is an integer
else
ciphertext[i] = argv[1][(int)(plaintext[i] - 'A')];
int ciphertext_casecheck = alphabet_case_check(ciphertext[i]);
if (plaintext_casecheck != ciphertext_casecheck){
if(plaintext_casecheck == 0){
ciphertext[i] = ciphertext[i] + ('a'-'A');
}
else if(plaintext_casecheck == 1){
ciphertext[i] = ciphertext[i] - ('a'-'A');
}
}
i++;
}
printf("ciphertext: %s", ciphertext);
return 0;
}
int check_key_validity(char argv[]){
return (calculate_key_size(argv) != 26) || (is_alphabet_arr(argv) == 1) || (repeat_letter_check(argv) == 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment