Untitled

mail@pastecode.io avatar
unknown
c_cpp
2 years ago
2.3 kB
2
Indexable
Never
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <stdlib.h>

char alphabet_small[26] =  {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
char alphabet_big[26] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
int main(int argc, string argv[])
{
    if (argc != 2 || strlen(argv[1]) != 26) // Error if number of arguments is not 1 or number of chars of the one arguemnt is not 26
    {
        printf("Usage: ./substitution key\n");
        return 1;
    }
    for (int i = 0; i < 26; i++)    // Check the 26 chars to see if they r from the alphabet
    {
        if (isalpha(argv[1][i]) == 0)
        {
            printf("Usage: ./substitution key\n");
            return 1;
        }
    }
    int l = 0;
    for (int m = 0; m < 26; m++)         // check the 26 letters,(compare each letter to the letters on its right)
    {
        for (int i = 1; i < 26; i++)                // check for the other 25 letters
        {
            if (argv[1][l] == argv[1][l + i] && l + i < 27)      // stop when l + i = 26 for each letter
            {
                printf("Usage: ./substitution key\n");
                return 1;
            }

        }
        l++;  // transition to next letter that needs to be checked
    }

    string s = get_string("plaintext:  ");
    for (int i = 0; i < strlen(s); i++)
    {
        if (s[i] >= 'a' && s[i] <= 'z')
        {
            for (int k = 0; k < 26; k++)
            {
                argv[1][k] = tolower(argv[1][k]);
                if (s[i] == alphabet_small[k])
                {
                    s[i] = argv[1][k];
                    k = 27;
                }
            }
        }
        else if (s[i] >= 'A' && s[i] <= 'Z')
        {
            for (int b = 0; b < 26; b++)
            {
                argv[1][b] = toupper(argv[1][b]);
                if (s[i] == alphabet_big[b])
                {
                    s[i] = argv[1][b];
                    b = 27;
                }
            }
        }
    }
    printf("ciphertext: %s\n", s);
    return 0;
}