My caesar.c
doesn't encrypt plaintext properly when there are non-alphabetical chars in my plaintext word. Here's my code for encryption:
int k = atoi(argv[1]);
string plain_text = GetString();
// declare int array of size equal to length of plain text string to use when encrypting with formula
int plain_text_num[strlen(plain_text)];
int n = strlen(plain_text);
for (int i = 0; i < n; i++)
{
if (isalpha(plain_text[i]) && isupper(plain_text[i]))
{
// convert from ASCII to alphabetical index for cap letters
plain_text_num[i] = plain_text[i] - 65;
}
else if (isalpha(plain_text[i]) && islower(plain_text[i]))
{
// convert from ASCII to alphabetical index for lower case
plain_text_num[i] = plain_text[i] - 97;
}
else
{
break;
}
}
for (int j = 0; j < n; j++)
{
plain_text_num[j] = (plain_text_num[j] + k) % 26;
}
for (int x = 0; x < n; x++)
{
if (isalpha(plain_text[x]) && isupper(plain_text[x]))
{
// convert from alphabetical index to ASCII for cap letters
plain_text_num[x] = plain_text_num[x] + 65;
}
else if (isalpha(plain_text[x]) && islower(plain_text[x]))
{
// convert from alphabetical index to ASCII for lower case
plain_text_num[x] = plain_text_num[x] + 97;
}
else
{
// store non-alphabetical chars in int array
plain_text_num[x] = plain_text[x];
}
}
for (int y = 0; y < n; y++)
{
printf("%c", plain_text_num[y]);
}
Here's my program's output when I try to cipher the plaintext string "world, say hello!" with 12 as a key:
The letters 'a'
and 'e'
get encrypted differently every time I run caesar
. "say hello" itself is also encrypted wrongly. But when I run caesar
with "worldsayhello!", I get what check50
expects.