#include <cs50.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdio.h>
int main(int argc, string argv[])
{
// Checks if there are two arguments.
if (argc != 2)
{
printf("Please input key.\n");
return 1;
}
// Checks if the key is only made of letters and has no repetitions.
for (int i = 0; argv[1][i] != '\0'; i++)
{
for (int j = 0; j < i; j++)
{
if (argv[1][j] == argv[1][i])
{
printf("Key must have 26 unique letters.\n");
return 1;
}
}
if (isdigit(argv[1][i]) != 0)
{
printf("Please input proper key.\n");
return 1;
}
if (!isalpha(argv[1][i]))
{
printf("Key must only contain letters.\n");
return 1;
}
if (strlen(argv[1]) != 26)
{
printf("Key must have 26 letters.\n");
return 1;
}
}
char alphabet[2][26];
for (int j = 0; j < strlen(argv[1]); j++)
{
alphabet[0][j] = 'A' + j;
alphabet[1][j] = argv[1][j];
}
// Gets input from user.
string text = get_string("Plaintext: ");
// Variable that stores the encrypted letter.
char ciphertext[strlen(alphabet[0])];
// Encrypting input from user.
for (int i = 0; i < strlen(text); i++)
{
if (isupper(text[i]))
{
for (int j = 0; j < strlen(argv[1]); j++)
{
if (alphabet[0][j] == text[i])
{
ciphertext[i] = toupper(alphabet[1][j]);
}
}
}
if (islower(text[i]))
{
for (int j = 0; j < strlen(argv[1]); j++)
{
if (tolower(alphabet[0][j]) == text[i])
{
ciphertext[i] = tolower(alphabet[1][j]);
}
}
}
else if (!isalpha(text[i]))
{
ciphertext[i] = text[i];
}
}
printf ("ciphertext: %s\n", ciphertext);
}
That's my code and it works pretty well, until I encrypt 35-36 character sentences or phrases with the last one being a period. It adds a letter or a non-ASCII character to the output. My question is, what's wrong with it?