Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <ctype.h>
- #include <cs50.h>
- #include <stdio.h>
- #include <string.h>
- #define ALPHABET 26
- int main(int argc, string argv[])
- {
- if (argc !=2) // invalid if there are more than two arguments
- {
- printf("Enter two arguments only.\n");
- return 1;
- }
- else
- {
- for (int i = 0, j = strlen(argv[1]); i < j; i++) // loop through each character of key to ensure its all alphabets
- {
- if (isalpha(argv[1][i]))
- {
- printf("Re-enter key with alphabets only.\n");
- return 1;
- }
- }
- }
- string key = argv[1]; // bind argument 1 to key variable
- string plaintext = get_string("plaintext: \n"); // prompt user for plaintext
- for (int i = 0, int j = 0, int pLength = strlen(plaintext); i < pLength; i++)
- {
- int keyLength = strlen(key); // get length of key
- char pLetter = plaintext[i]; // bind each character of plaintext to pLetter
- char kLetter = argv[1][j % keyLength]; // bind each character of key to kLetter
- if (isupper(kLetter)) // get alphabet index of key if its uppercase
- {
- kLetter -= 65;
- }
- else if (islower(kLetter)) // get alphabet index of key if its lowercase
- {
- kLetter -= 97;
- }
- if (isupper(plaintext[i])) // add key to upper plaintext character, deduct 65, module by 26 and add back 65 to get ASCII value
- {
- printf("%c", (((plaintext[i] + kLetter - 65) % ALPHABET) + 65);
- j++; // increment j by 1 to loop through each character of key
- }
- else if (islower(plaintext[i])) // add key to lower plaintext character, deduct 97, module by 26 and add back 97 to get ASCII value
- {
- printf("%c", (((plaintext[i] + kLetter - 97) % ALPHABET) + 97);
- j++;
- }
- else
- {
- printf("%c", plaintext[i]); // if plaintext is neither upper or lower, print character as is
- }
- }
- printf("\n");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement