Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cs50.h>
- #include <ctype.h>
- #include <stdio.h>
- #include <string.h>
- int main(int argc, string argv[])
- {
- // check for 26 characters in key, check to make sure there are right amount of cmd line arguments
- if (argc != 2)
- {
- printf("Usage: ./substitution (key)\n");
- return 1;
- }
- // is it a letter?
- string cipherkey = argv[1];
- int len = strlen(cipherkey);
- for (int i = 0; i < len; i++)
- {
- if (!isalpha(cipherkey[i]))
- {
- printf("Usage: ./substitution (key)\n");
- return 1;
- }
- // is it 26 characters?
- if (len != 26)
- {
- printf("Key must be 26 characters!\n");
- return 1;
- }
- // has to be 26 diff alphabet
- for (int first = 0; first < len; first++)
- {
- for (int second = first + 1; second < len; second++)
- {
- if (toupper(cipherkey[first]) == toupper(cipherkey[second]))
- {
- printf("Usage: ./substitution (key)\n");
- return 1;
- }
- }
- }
- }
- // run actual cipher decoding part
- string text = get_string("plaintext: ");
- for (int i = 0; i < len; i++)
- {
- if (islower(cipherkey[i]))
- {
- cipherkey[i] = cipherkey[i] - 32; // difference between upper and lower case letter equivalent in ASCII ('A' - 'a' = 32 for example)
- }
- }
- // final result, look for if the index is upper or lower case
- printf("ciphertext: ");
- for (int i = 0; i < len; i++)
- {
- if (isupper(text[i]))
- {
- int upperpos = text[i] - 65;
- printf("%c", cipherkey[upperpos]); // print result of math, make it an index of cipher key to print later
- }
- else if (islower(text[i]))
- {
- int lowerpos = text[i] - 97;
- printf("%c", cipherkey[lowerpos] + 32);
- }
- else printf("%c", text[i]);
- }
- printf("\n");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement