This problem set requires us to code a programme that takes a key from the user from the CLI and then an input (plaintext) and return a ciphertext version that is scrambled based on the key provided.
My code returns the correct ciphertext given any key and plaintext, however, the apparent output when using the in-built check50 module from cs50 is "", an empty string.
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
string encrypt(string keys, string inputs);
char newkey;
string ciphertext;
int main(int argc, string argv[])
{
if (argc == 1)
{
printf("Please enter a key!\n");
return 1;
}
if (argc > 2)
{
printf("You can only have one key. The key must not have any spaces!\n");
return 1;
}
if (0 < strlen(argv[1]) && strlen(argv[1]) < 26)
{
printf("Key must contain 26 characters!\n");
return 1;
}
for (int j = 0; j < strlen(argv[1]); j++)
{
if (!((argv[1][j] >= 'a' && argv[1][j] <= 'z') || (argv[1][j] >= 'A' && argv[1][j] <= 'Z')))
{
printf("Key must contain alphabets only!");
return 1;
}
}
for (int k = 0; k < strlen(argv[1]); k++)
{
for (int l = (k + 1); l < strlen(argv[1]); l++)
{
if (argv[k] == argv[l])
{
printf("There can be no duplicate alphabets in the key!");
return 1;
}
}
}
string key = argv[1];
string input = get_string("plaintext: ");
encrypt(key, input);
printf("ciphertext: %s\n", ciphertext);
}
string encrypt(string keys, string inputs)
{
char ciphertexts[strlen(inputs)];
for (int i = 0; i < strlen(inputs); i++)
{
if (islower(inputs[i]))
{
int index = inputs[i] - 97;
newkey = keys[index];
ciphertexts[i] = tolower(newkey);
}
else if (isupper(inputs[i]))
{
int index = inputs[i] -65;
newkey = keys[index];
ciphertexts[i] = toupper(newkey);
}
else
{
ciphertexts[i] = inputs[i];
}
}
ciphertext = ciphertexts;
printf("%s\n",ciphertexts);
printf("%s\n",ciphertext);
return ciphertext;
}
The errors are as follows:
:( encrypts "A" as "Z" using ZYXWVUTSRQPONMLKJIHGFEDCBA as key
expected "ciphertext: Z\...", not ""
This means that using a key of ZYXWVUTSRQPONMLKJIHGFEDCBA, and a plaintext of "A", "Z" is expected, but my programme outputs "".
I have a printf statement printing the cipher text, but it is somehow not captured