0

I am wondering what this code is doing wrong when I run the keyword, "illuminatti," and the plaintext, "Magick is the key". I should get the ciphertext, "Ulrcos vs mam spj". I instead get the ciphertext, "Ulr}os vs {m kr{". Why am I printing one character short and what tips can you give me to wrap around the keyword.

#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

int main(int argc, string argv[])
{

if (argc != 2)
{
    printf("Error\n");
    return 1;
}

for (int i = 0, n = strlen(argv[1]); i < n; i++)
{
    if (!isalpha(argv[1][i]))
    {
        printf("Error\n");
        return 1;
    }
}

int count = 0, keytext = 0, keychar = 0;

printf("plaintext: ");
string plaintext = get_string();

while (plaintext[count] != '\0')
{
    count++;
}

while (argv[1][keytext] != '\0')
{
    keytext++;
}

if (plaintext != NULL)
{

    printf("ciphertext: ");

    for (int j = 0; j < keytext; j++)
    {
        if (isupper(argv[1][j]))
        {
            argv[1][j] = argv[1][j] - 65;
        }

        else if (islower(argv[1][j]))
        {
            argv[1][j] = argv[1][j] - 97;
        }
    }

    for (int i = 0; i < count; i++)
    {
        if (!ispunct(plaintext[i]) && !isdigit(plaintext[i]) && !isspace(plaintext[i]) && isalpha(plaintext[i]))
        {
            printf("%c", plaintext[i] + argv[1][keychar] % 26);
            keychar++;
        }

        else if (ispunct(plaintext[i]) || isspace(plaintext[i]) || isdigit(plaintext[i]))
        {
            printf("%c", plaintext[i]);
        }
    }

    printf("\n");

}
}
0

I don't seem to get where you wrap around in the key (like for example some keychar % keytext)? If you don't wrap around, you accidentally read the bytes stored after the key, whatever that is. Many bytes are initially zero, that's why much of your output looks like the input.

Also, what do you think 'Z'+7 is? It's a, and not what you want. You need to wrap around after Z/z, an easy way is for uppercase letters to first subtract 'A', add the key, apply the % 26, and then add 'A' again. Would be 'a' for lowercase letters instead.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .