Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <cs50.h>
- #include <string.h>
- //for character classification functions
- #include <ctype.h>
- //function declaration
- bool validate(string key);
- //global variable
- string abc = "abcdefghijklmnopqrstuvwxyz";
- int main(int argc, string argv[])
- {
- string key = NULL, plaintext = NULL, ciphertext = NULL; //Create variable outside if statement. Otherwise if the statement isn't true the variable isn't created for later use.
- int length; //Generally good practice to create all your variables at the top and only create variables that only need to be used once within your loops.
- if (argc == 2)
- {
- key = toupper(argv[1]); //Keeping the key as uppercase.
- }
- else
- {
- printf("Usage: ./substitution key \n");
- return 1;
- }
- if (!validate(key)) //No need to write == true, just putting a function in brackets like (validate(key)) is checking if it returns true, the ! checks if it's false, just a small change to help with readability.
- {
- printf("Key must contain 26 unique characters\n");
- return 1;
- }
- plaintext = get_string("plaintext: ");
- length = strlen(plaintext);
- for(int i = 0; i < length; i++)
- {
- if (isupper(plaintext[i]) != 0)
- {
- for (int j = 0; j < 26; j++ )
- {
- if (abc[j] == tolower(plaintext[i])) //Problem is how you're handling copying your arrays.
- {
- ciphertext[i] = toupper(key[j]);
- break;
- }
- }
- }
- else if (islower(plaintext[i]) != 0)
- {
- for (int j = 0; j < 26; j++ )
- {
- if (abc[j] == plaintext[i])
- {
- ciphertext[i] = tolower(key[j]);
- break;
- }
- }
- }
- else
- {
- ciphertext[i] = plaintext[i];
- }
- }
- printf("ciphertext: %s\n", ciphertext);
- return 0;
- }
- bool validate(string key)
- {
- int match_counter = 0;
- if (strlen(key) == 26)
- {
- for (int i = 0; i < 26; i++)
- {
- for (int j = 0; j < 26; j++)
- {
- if(tolower(key[j]) == abc[i])
- {
- match_counter++;
- break;
- }
- }
- }
- if(match_counter == 26)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- else
- {
- return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement