Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cs50.h>
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #include <ctype.h>
- int main(int argc, string argv[])
- {
- //Check correct # of characters
- if (argc != 2)
- {
- printf("Error!\n");
- return 1;
- }
- //reject if there are non-alphabet characters in keyword
- for (int i = 0; i < strlen(argv[1]); i++)
- {
- if (!isalpha(argv[1][i]))
- {
- printf("Error!\n");
- return 1;
- }
- }
- int keylength = strlen(argv[1]);
- if (argc == 2)
- {
- //get the plaintext
- string plain = get_string("plaintext: ");
- int plainlength = strlen(plain);
- printf("ciphertext: ");
- //for each character in the plaintext
- for (int i = 0, s = 0; i < plainlength; i++)
- {
- //if it's an alphabet
- if (isalpha(plain[i]))
- {
- int key = (tolower(argv[1][s % keylength])) - 97;// key
- //if it's lowercase
- if (islower(plain[i]))
- {
- int lowercipher = (((plain[i] + key) - 97) % 26) + 97;
- printf("%c", lowercipher);
- s++;
- }
- // if it's uppercase, do same thing as lowercase but change to uppercase in the end
- if (isupper(plain[i]))
- {
- int uppercipher = (((tolower(plain[i]) + key) - 97) % 26) + 97;
- printf("%c", toupper(uppercipher));
- s++;
- }
- }
- //if it's any other character, print that character
- else
- {
- printf("%c", plain[i]);
- }
- }
- //line break after plaintext is converted to ciphertext
- printf("\n");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement