I'm having a problem with an output. Sometimes output adds an extra characters, different each time the code runs. For example, when I use key "1" and write "a", it displays "bç" or "bv" or anything else weird.
I know that the problem may be fixed by adding "+1" in a loop here
for (int i = 0; i < text_length; i++)
. Also I know that the problem is because at the end of the string is '\0' character.
But the things is that plaintext length = ciphertext length. So even in the loop there should be NO problems.
So I don't understand why it's fixed by adding +1 in a loop and I don't understand why it needs to add +1.
Please, explain this to me.
debug50 and variable tracking hasn't helped.
Here's what I found so far on this issue: Pset2 Caesar: extra letter printed at the end of ciphertext
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
int main(int argc, string argv[])
{
// check if there's only one argument provided
if (argc != 2)
{
printf("Usage: ./caesar key\n");
return 1;
}
// check if argument is digit
string string_key = argv[1];
for (int i = 0, n = strlen(string_key); i < n; i++)
{
if (isdigit(string_key[i]) == false)
{
printf("Usage: ./caesar key\n");
return 1;
}
}
// convert string_key to int
int key = atoi(string_key);
// prompt user for a string to encipher
string plaintext;
do
{
plaintext = get_string("plaintext: ");
}
while (plaintext[0] == '\0');
int UPPERCASE_DIFFERENCE = 65;
int LOWERCASE_DIFFERENCE = 97;
// get length of plaintext
int text_length = strlen(plaintext);
// create ciphertext array with length of plaintext
char ciphertext[text_length];
// loop through plaintext
char character;
for (int i = 0; i < text_length; i++)
{
character = plaintext[i];
// check if character is a letter
if (isalpha(character))
{
// check if character is an uppercase
if (isupper(character))
{
// convert to alphabetical numbers, shift to key, convert back to ascii
character = character - UPPERCASE_DIFFERENCE;
character = (character + key) % 26;
character = character + UPPERCASE_DIFFERENCE;
// add to ciphertext
ciphertext[i] = character;
}
else
{
// convert to alphabetical numbers, shift to key, convert back to ascii
character = character - LOWERCASE_DIFFERENCE;
character = (character + key) % 26;
character = character + LOWERCASE_DIFFERENCE;
// add to ciphertext
ciphertext[i] = character;
}
}
else
{
ciphertext[i] = character;
}
}
// print ciphertext
printf("ciphertext: %s\n", ciphertext);
}
ciphertext[i + 1] = '\0';
at the end of a loop. I think that the error was because I didn't have an explicit ending '\0' of the char ciphertext array. But why didn't it work with length in a loop? Also how length + 1 fixes the issue?