Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cs50.h>
- #include <ctype.h>
- #include <stdio.h>
- #include <string.h>
- int main(int argc, string argv[])
- {
- // Validate key length
- if (argc == 2)
- {
- string key = argv[1];
- int key_len = strlen(key);
- // Check key is 26 characters, and alphabetic
- for (int i = 0, n = key_len; i < key_len; i++)
- {
- if (key_len < 26 && isalpha(key[i]))
- {
- printf("Key must contain 26 characters.\n");
- return 1;
- }
- if (key_len > 26 && isalpha(key[i]))
- {
- printf("Key must contain 26 characters.\n");
- return 1;
- }
- }
- // Reject digits
- int j = 0;
- if (isdigit(key[j]))
- {
- printf("Usage: ./substitution key\n");
- return 1;
- }
- // Check for duplicate letters
- for (int q = 0; q < key_len; q++)
- {
- for (int w = q + 1; w < key_len; w++)
- {
- if (key[q] == key[w])
- {
- printf("Key must not contain repeated characters.\n");
- return 1;
- }
- }
- }
- // Collect plaintext
- string s = get_string("plaintext: ");
- // Output encrypted text
- printf("ciphertext: ");
- for (int o = 0, m = strlen(s); o < m; o++)
- {
- if (isalpha(s[o]) && isupper(s[o]))
- {
- int upper = s[o] - 'A';
- printf("%c", toupper(key[upper]));
- }
- else if (isalpha(s[o]) && islower(s[o]))
- {
- int lower = s[o] - 'a';
- printf("%c", tolower(key[lower]));
- }
- else
- {
- printf("%c", s[o]);
- }
- }
- printf("\n");
- return 0;
- }
- // User inputs more than a single key
- if (argc != 2 || isdigit(argv[1]))
- {
- printf("Usage: ./substitution key\n");
- return 1;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement