Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <cs50.h>
- #include <stdlib.h>
- #include <ctype.h>
- #include <string.h>
- #include <math.h>
- //Get the key right from the command line argument
- int main(int argc, string argv[])
- {
- //if the key has more or less than a single character and if the keyword is not alphabetical, end the program
- if (argc != 2)
- {
- printf("You must enter a single string as the key\n");
- return 1;
- }
- for (int k = 0, n = strlen(argv[1]); k < n; k++)
- {
- while (!isalpha(argv[1][k]))
- {
- printf("The key must be alphabetical\n");
- return 1;
- }
- }
- //Prompt the user for the plaintext
- string plaintext = get_string("Write a text to encrypt: ");
- string keyword = argv[1];
- int s = strlen(plaintext);
- //Print the response previous to the ciphering
- printf("ciphertext: ");
- //iterate over every plaintext and keyword character
- for (int i = 0, j = 0, n = strlen(keyword); i < s; i++)
- {
- //check if the plaintext character is alphabetic
- if (isalpha(plaintext[i]))
- {
- //Preserve upper cases and lower cases of each character
- if (isupper(plaintext[i]))
- {
- printf("%c", ((plaintext[i] - 65 + keyword[j] - 65) % 26 + 65));
- j = (j + 1) % n;
- }
- if (islower(plaintext[i]))
- {
- printf("%c", ((plaintext[i] - 97 + keyword[j] - 97) % 26 + 97));
- j = (j + 1) % n;
- }
- }
- //Print the non-alphabetic characters without applying the keyword
- else
- {
- printf("%c", plaintext[i]);
- }
- }
- printf("\n");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement