Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <cs50.h>
- #include <string.h>
- #include <ctype.h>
- int main(int argc, string argv[])
- {
- //must provide key
- if (argc != 2)
- {
- printf("USAGE: ./substitution 26KEY\n");
- return 1;
- }
- //store key in a new variable
- string key = argv[1];
- //check if key is 26 long
- if (strlen(key) != 26)
- {
- printf("Key must contain 26 characters.\n");
- return 1;
- }
- //check if all 26 characters are acctually letters
- for (int i=0; i<strlen(key); i++)
- {
- if (isalpha(key[i]) == 0)
- {
- printf("Key must contain letters only.\n");
- return 1;
- }
- }
- //check if any letters are repeated
- //check each letter and keep track in an array called "used"
- //eg: When you see the letter A in the key, you set position 1 as true
- //if its already set to true, that means you already had that letter in the key
- bool used[26] = {};
- int pos=0;
- for (int i=0; i<strlen(key); i++)
- {
- pos=toupper(key[i])-65;
- if (used[pos] == true)
- {
- printf("Key can't repeat letters.\n");
- return 1;
- }
- else
- {
- used[pos] = true;
- }
- }
- string plaintext="";
- //get word to encrypt
- plaintext = get_string("plaintext: ");
- //how to substitute each letter using the 26KEY?
- //loop through the entire word...
- //get position of each letter (eg: a=1, b=2, etc)
- //then look up that position in the 26KEY and print that letter
- int position=0;
- char oldChar;
- char newChar;
- printf("ciphertext: ");
- for (int i=0; i<strlen(plaintext); i++)
- {
- oldChar = plaintext[i];
- //only translate letters
- if (isalpha(oldChar) == 0)
- {
- printf("%c", oldChar);
- }
- else
- {
- //translate a-z to 0-25 position to look up in the key
- position = toupper(oldChar)-65;
- newChar = key[position];
- //preserve the case of the original letter, regardless of case in the key
- //ie: lower stays lower, upper stays upper
- if (islower(oldChar))
- {
- newChar=tolower(newChar);
- }
- else
- {
- newChar=toupper(newChar);
- }
- printf("%c",newChar);
- }
- }
- printf("\n");
- }
Add Comment
Please, Sign In to add comment