Why my ciphered text string is longer than expected?
I'm facing the CS50's substitution problem. It works, even though the code is not very optimized.
The problem is that i had to add this line of code at the end to make it work: `
cipher_text[strlen(plain_text)] = '\0';
`
otherwise the lenght of the cipher_text is longer than expected.
Can you tell me why?
this is the code i've written.
`
#include
#include
#include
#include
int main(int argc, string argv[])
{
// check if there's 1 argument, if there are > 1 or < 0 print error message and return 1
if (argc != 2)
{
printf("Error, type 1 command\n");
return 1;
}
string key = argv[1];
long lenght = strlen(key);
// check if the key is valid (26 characters) or not, if not return 1 and print error
if (lenght != 26)
{
printf("Key must contain 26 characters.\n");
return 1;
}
// iterate throughout the key, element after element whith the 1st for loop
//check if contains letters or something else in the 1st if
//make the key all lower in order to compare letter repetition in the else if
//check for double letters (compare every letter (key[i]) with all the other letters) in the second for loop
for (int i = 0 ; i < lenght ; i++)
{
if (isalpha(key[i]) == 0) //(key[i] < 65 || key[i] > 90) && (key[i] < 97 || key[i] > 122))
{
printf("Key must contain only letters\n");
return 1;
}
else if (isupper(key[i]))
{
key[i] = tolower(key[i]);
}
for (int j = 0 ; j < lenght ; j++)
{
if (j != i && key[j] == key[i])
{
printf("You can't repeat letters in key (you've repeated the letter %c)\n", key[j]);
return 1;
}
}
}
//ask user for the text to cipher
string plain_text = get_string("plaintext: ");
char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
char ALPHABET[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char cipher_text[strlen(plain_text)];
// iterate through every index in plain_text
//if it is not alphabetical, add it to cipher text
//otherwise, check if it is lower or upper, and add to cipher_text
//
for (int j = 0; j < strlen(plain_text) ; j++)
{
if (isalpha(plain_text[j]) == 0)
{
cipher_text[j] = plain_text[j];
}
for (int x = 0 ; x < lenght ; x++)
{
if(islower(plain_text[j]))
{
if (plain_text[j] == alphabet[x])
{
cipher_text[j] = key[x];
}
}
else if (isupper(plain_text[j]))
{
if (plain_text[j] == ALPHABET[x])
{
cipher_text[j] = toupper(key[x]);
}
}
}
}
cipher_text[strlen(plain_text)] = '\0';
printf("ciphertext: %s\n", cipher_text);
return 0;
}
`