Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <cs50.h>
- #include <string.h>
- #include <stdlib.h>
- #include <ctype.h>
- int main (int argc, string argv[])
- {
- //error if no key given
- if (argc < 2)
- {
- printf("\nI'll need a key at the command prompt!\n\n");
- return 1;
- }
- //error if too much keys given
- else if (argc > 2)
- {
- printf("\nThat's too much!\n\n");
- return 1;
- }
- //and for the right amount of arguments we can continue
- else
- {
- string key = argv[1];
- //check for invalid chars in keyword
- for (int i = 0, n = strlen(key); i < n; i++)
- {
- if (!(isalpha(key[i])))
- {
- printf("\nI'll need a keyword, only letters!\n\n");
- return 1;
- }
- }
- //close the checkalpha iteration and ask for phrase to crypt
- string plaintext = GetString();
- int k = 0; //to correct for skipped plaintextchars
- //iterate through plaintext array we just got
- for (int i = 0, n = strlen(plaintext); i < n; i++)
- {
- int j = i % strlen(key);
- //branch for all non-alphabetic chars
- if (!(isalpha(plaintext[i])))
- {
- printf("%c", plaintext[i]);
- k++;
- }
- //branch for all alphabetic chars in plaintext
- else
- {
- //declare conversion constant for upper & lower case letters
- int a = 65;
- int b = 97;
- //branch for all uppercase chars in plaintext
- if (isupper(plaintext[i]))
- {
- int convertedPlaintext = plaintext[i] - a;
- if (isupper(key[j]))
- {
- int convertedKey = key[j - k] - a;
- int result = (convertedPlaintext + convertedKey) % 26;
- printf("%c", result + a);
- }
- else //islower
- {
- int convertedKey = key[j - k] - b;
- int result = (convertedPlaintext + convertedKey) % 26;
- printf("%c", result + a);
- }
- }
- //branch for all lower case chars in OGPhrase
- else
- {
- int convertedPlaintext = plaintext[i] - b;
- if (isupper(key[j]))
- {
- int convertedKey = key[j - k] - a; //is a still 65 here scopewise?
- int result = (convertedPlaintext + convertedKey) % 26;
- printf("%c", result + b);
- }
- else
- {
- int convertedKey = key[j - k] - b;
- int result = (convertedPlaintext + convertedKey) % 26;
- printf("%c", result + b);
- }
- }
- }
- }
- printf("\n");
- return 0;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement