Untitled

mail@pastecode.io avatar
unknown
c_cpp
a month ago
2.1 kB
3
Indexable
Never
// including header files
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>

// constants
const int ALPHABET = 26;

// prototypes
bool check_valid_keys(string s);

int main(int argc, string argv[])
{
    // checking for command line argument exceptions
    if (argc != 2)
    {
        // checking the number of CL arguments
        printf("Usage: ./substitution key\n");
        return 1;
    }
    else if (strlen(argv[1]) != ALPHABET)
    {
        // checking if the length of the key is exactly 26
        printf("Key must contains %i letter\n", ALPHABET);
        return 1;
    }
    else if (!check_valid_keys(argv[1]))
    {
        // checking if the key of 26 lenghts contains all the alphabet
        printf("Key must contains %i distinct letter\n", ALPHABET);
        return 1;
    }

    // taking user input and getting key
    string text = get_string("plaintext:  ");
    string key = argv[1];

    // transforming key to all upercase
    for (int i = 0; i < ALPHABET; i++)
    {
        key[i] = toupper(key[i]);
    }

    // encrypting text
    for (int i = 0, n = strlen(text); i < n; i++)
    {
        if (islower(text[i]))
        {
            text[i] = tolower(key[(int) text[i] - (int) 'a']);
        }
        else if (isupper(text[i]))
        {
            text[i] = key[(int) text[i] - (int) 'A'];
        }
    }

    // printing encrypted text
    printf("ciphertext: %s\n", text);
    return 0;
}

bool check_valid_keys(string s)
{
    // creating an array of boolean consisting of 26 false value
    bool check[ALPHABET];
    for (int i = 0; i < ALPHABET; i++)
    {
        check[i] = false;
    }

    // checking each alphabet
    for (int i = 0; i < ALPHABET; i++)
    {
        s[i] = toupper(s[i]);
        if (s[i] >= 'A' && s[i] <= 'Z')
        {
            check[s[i] - 'A'] = true;
        }
    }

    for (int i = 0; i < ALPHABET; i++)
    {
        if (!check[i])
        {
            return false;
        }
    }
    return true;
}
Leave a Comment