Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cs50.h>
- #include <ctype.h>
- #include <stdio.h>
- // #include <stdlib.h>
- #include <string.h>
- string encipher(string plaintext, string cipher);
- int main(int argc, string argv[])
- {
- //string cipher = argv[1];
- //Validate the key
- bool hasRepeats = false;
- bool nonletters = false;
- //Make sure theres a key
- if (argc != 2)
- {
- printf("Usage: ./substitution key\n");
- return 1;
- }
- for (int i = 0, n = strlen(argv[1]); i < n; i++)
- {
- for (int j = 0, m = strlen(argv[1]); j < n; j++)
- {
- if (i == j)
- {
- //comparing to self, do nothing
- }
- else
- {
- // Check for repeated letters
- if ((toupper(argv[1][i])) == toupper(argv[1][j]))
- {
- hasRepeats = true;
- }
- }
- //return 0;
- }
- // Check for numbers in the argv[1]
- if (isalpha(argv[1][i]) == 0)
- {
- nonletters = true;
- }
- }
- if (argc == 2 && strlen(argv[1]) != 26)
- {
- printf("Key must contain 26 characters.\n");
- return 1;
- }
- else if (nonletters == true)
- {
- printf("Key must only contain alphabetic characters.\n");
- return 1;
- }
- else if (hasRepeats == true)
- {
- printf("Key must not contain repeated characters.\n");
- return 1;
- }
- else
- {
- // printf("Looks good, baby!\n");
- }
- //Ask for the user text
- string plaintext = get_string("plaintext: \n");
- //Encipher the text
- string ciphertext = encipher(plaintext, argv[1]);
- //Print the ciphertext
- printf("ciphertext: %s\n", ciphertext);
- return 0;
- }
- string encipher(string plaintext, string cipher)
- {
- char encoded[strlen(plaintext)];
- for (int i = 0, n = strlen(plaintext); i < n; i++)
- {
- bool lowerCase = false;
- if (isalpha(plaintext) == true)
- {
- if (islower(plaintext[i]) == true)
- {
- lowerCase = true;
- }
- int position = toupper(plaintext[i]) - 65;
- encoded[i] = cipher[position];
- //correct to lowercase
- if (lowerCase == true)
- {
- encoded[i] = tolower(encoded[i]);
- }
- }
- else
- {
- encoded[i] = plaintext[i];
- }
- }
- return encoded;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement