My caesar code has been working perfectly (passed the check50) until I tried to decrypt an 8-character message and discovered that for this number of characters I get a B printed at the end of my cipher text. I tried debugging and it seems that the program loops through my letters correctly (works fine if I just print every character to the screen separately) and only at the very final stage as I try to print the whole string the B is added. I would like to know the reason for this error - what happens for this particular string length that causes this to occur?
I'm still a very beginner so I appreciate any help.
Here's my code:
//Function accepts exactly one command-line argument
int main(int argc, string argv[])
{
if (argc == 2)
{
int k = atoi(argv[1]); //Convert to integer
if (k > 26) //Wrap around the alphabet (only letters)
{
k = k % 26;
}
//Prompt user for text
printf("plaintext: ");
string plain_text = get_string();
//Convert into cipher
int length = strlen(plain_text);
char cipher_text[length];
for (int i = 0; i < length; i++)
{
//If lower case
int wrap;
if (plain_text[i] >= 97 && plain_text[i] <= 122)
{
wrap = 122 - plain_text[i]; //amount before z
if (k > wrap) //To wrap back to a
{
cipher_text[i] = 96 + (k - wrap);
}
else if (k <= wrap)
{
cipher_text[i] = plain_text[i] + k;
}
}
//If upper case
else if (plain_text[i] >= 65 && plain_text[i] <= 90)
{
wrap = 90 - plain_text[i]; //amount before Z
if (k > wrap)//To wrap back to A
{
cipher_text[i] = 64 + (k - wrap);
}
else if (k <= wrap)
{
cipher_text[i] = plain_text[i] + k;
}
}
//Leave non-alphabetical characters unchanged
else
{
cipher_text[i] = plain_text[i];
}
printf("%c", cipher_text[i]); //Print individual characters to check
}
//Print the converted text
printf("\n");
printf("ciphertext: %s\n", cipher_text);
return 0;
}
//If no or too many command-line arguments, print error message and return 1
else
{
printf("Please use exactly one command-line argument.\n");
return 1;
}
}
Here's an example of the output I get:
~/workspace/pset2/caesar/ $ ./caesar 1
plaintext: H Knud T
I Love U
ciphertext: I Love UB