Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cs50.h>
- #include <stdio.h>
- #include <ctype.h>
- #include <string.h>
- #include <stdlib.h>
- int validate (char* key);
- char* ciphrate (char* text, char* key);
- int main (int argc, string argv[])
- {
- int valid = validate(argv[1]); //call function to validate the key is 26 char long, no char repeated and no numebers on it
- if (valid != 0)
- { //prints an error code
- if(valid == 1)
- {
- printf("Usage ./usability KEY\n");
- }
- else if (valid == 2)
- {
- printf("The key must contain 26 alphabetic characters\n");
- }
- else if (valid == 3)
- {
- printf("The key must contain no repeated characters\n");
- }
- else if (valid == 4)
- {
- printf("The key must not contain digits\n");
- }
- return 1; //return a code error
- }
- char* plaintxt = get_string("Plaintext: "); //ask for text to encipher
- printf("\n");
- char* ciphertxt = ciphrate(plaintxt, argv[1]); //call function to encipher the text
- printf("Ciphertext: %s\n", ciphertxt); //prints the result text
- return 0;
- }
- int validate (char* key)
- {
- int lenght = strlen(key); //checks for key lenght
- int chars = 0, a = 0, b = 0, c = 0; //some variables
- if (lenght != 26) //checks if lenght isn't equal to 26
- {
- return 2; //second error code output
- }
- for(int k = 0; k < 26; k++)
- {
- a = isdigit(key[k]); //check every char for a digit and add a value to a
- }
- if (a != 0) //if there's a digit
- {
- return 4; //fourth error code output
- }
- for(int i = 0; i < 26; i++)
- {
- c = islower(key[i]);
- if (c != 0)
- {
- key[i] = toupper(key[i]); //transform all chars to uppercase
- }
- b = b + key[i];
- }
- if (b != 2015) //the sum of all A - Z chars is 2015
- {
- return 3; //third error code output
- }
- return 0; //no error code output
- }
- char* ciphrate (char* text, char* key)
- {
- int text_lenght = strlen(text);
- char* ciphrated_text = NULL;
- for(int i = 0; i < text_lenght; i++)
- {
- int d = 0, e = 0,f = 0;
- d = isupper(text[i]); //checks if cahr is uppercase or lower
- e = islower(text[i]);
- if(d == 0)
- {
- f = text[i] - 65; //if it's uppercase then substract 65 (for knowing in witch place of the alphabet it's located)
- ciphrated_text[i] = key[f]; //and then assign the letter in the key that is in that possition
- }
- else if(e == 0)
- {
- f = text[i] - 97; //if it's a lowercase then substract 97 (same reason as in uppercase)
- ciphrated_text[i] = key[f] + 32; //assign the letter in the key and add 32 so it's still a lowercase
- }
- }
- return ciphrated_text; //return the ciphrated text
- }
Add Comment
Please, Sign In to add comment