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>
- #include <stdlib.h>
- string substitutioncipher(string plaintext, string key);
- int main(int argc, string argv[])
- {
- //First we check there are only 2
- if (argc != 2)
- {
- printf("./substitution key\n");
- return 1;
- }
- //we check that there are exactly 26 letters
- int arglen = strlen(argv[1]);
- if (arglen != 26)
- {
- printf("Key must contain 26 characters.\n");
- return 1;
- }
- //we check they are only leters and get the key and uppercase it
- string key = argv[1];
- for (int i = 0; i < arglen; i++)
- {
- if (!isalpha(key[i]))
- {
- printf("The key must only contain letters\n");
- return 1;
- }
- key[i] = toupper(key[i]);
- }
- //now we check for duplicate characters
- //Basically we do a double loop checking if any character is equal to another
- //We also put a not equal there so characters in the same spot dont trigger the check
- for (int i = 0; i < 26; i++)
- {
- for (int j = 0; j < 26; j++)
- {
- if (key[i] == key[j] && i != j)
- {
- printf("No duplicate characters allowed in key\n");
- return 1;
- }
- }
- }
- string plaintext = get_string("plaintext: ");
- string ciphertext = substitutioncipher(plaintext, key);
- int plenght = strlen(ciphertext);
- /*
- char teststring[plenght];
- strcpy(teststring, ciphertext);
- string ciphertexttest = teststring;
- ciphertexttest[plenght] = '\0';
- */
- ciphertext[plenght] = '\0';
- printf("ciphertext: %s\n", ciphertext);
- //printf("ciphertexttest: %s\n", ciphertexttest);
- return 0;
- }
- string substitutioncipher(string plaintext, string key)
- {
- int lenght = strlen(plaintext);
- char cyphertextArr[lenght];
- cyphertextArr[lenght] = '\0';
- string cyphertext = cyphertextArr;
- for (int i = 0; i < lenght; i++)
- {
- if (isupper(plaintext[i]))
- {
- int cur_letter = plaintext[i] - 'A';
- char cyp_letter = key[cur_letter];
- cyphertext[i] = toupper(cyp_letter);
- }
- else if (islower(plaintext[i]))
- {
- int cur_letter = plaintext[i] - 'a';
- char cyp_letter = key[cur_letter];
- cyphertext[i] = tolower(cyp_letter);
- }
- else
- {
- cyphertext[i] = plaintext[i];
- }
- }
- return cyphertext;
- }
Advertisement
Add Comment
Please, Sign In to add comment