Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cs50.h>
- #include <stdio.h>
- #include <string.h>
- #include <ctype.h>
- char char_index(char c);
- int main(int argc, string argv[])
- {
- //ensure correct amount of args
- if (argc != 2)
- {
- printf("Usage: ./substitution key\n");
- return 1;
- }
- string key = argv[1];
- int key_length = strlen(key);
- //check if key has exactly 26 chars
- if (key_length != 26)
- {
- printf("Key must contain 26 characters.\n");
- return 1;
- }
- //check if key has only alphabetic chars and no repeating char
- for (int i = 0; i < key_length; i++)
- {
- if (!isalpha(key[i]))
- {
- printf("key must be contain only alphabetic characters");
- return 1;
- }
- //double check, literally, if a char has been seen before
- for (int j = 0; j < key_length; j++)
- {
- if (i != j)
- {
- if (key[i] == key[j])
- {
- printf("key must contain unique characters");
- return 1;
- }
- }
- }
- }
- string plaintext = get_string("Plaintext: ");
- int length = strlen(plaintext);
- string ciphertext[length];
- printf("ciphertext: ");
- for (int i = 0; i < length; i++)
- {
- //if this letter is a char
- char plain_char = plaintext[i];
- if (isalpha(plain_char))
- {
- int index = char_index(plaintext[i]);
- char cipher_char = key[index];
- if (isupper(plain_char))
- {
- cipher_char = toupper(cipher_char);
- }
- else
- {
- cipher_char = tolower(cipher_char);
- }
- printf("%c", cipher_char);
- }
- else
- {
- printf("%c", plain_char);
- }
- }
- printf("\n");
- }
- //get the index of each char to be used in the key
- char char_index(char c)
- {
- int index = 0;
- //determine the positional value of char
- if (isupper(c))
- {
- index = ((int) c) - 65;
- }
- else if (islower(c))
- {
- index = ((int) c) - 97;
- }
- return index;
- //use this to determine the value of cipherchar
- //return cipher
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement