0

Some of my plaintext is encrypted correctly but some are not, which I could not figure out why. Here's my code:

// Program that encrypts messages using Vigenère’s cipher

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

int main(int argc, char *argv[])
{
    if (argc == 2)
    {

        // Prompt user for plaintext
        string plain;
        plain = get_string("plaintext: ");

        printf("ciphertext: ");

        // Iterate over each character of plaintext
        for (int i = 0; i < strlen(plain); i++)
        {

            int key = strlen(argv[1]);
            {
                // Shift character by key if it is an alphabet
                if (isalpha(plain[i]))
                {
                    // Preserve case for alphabets
                    if (isupper(plain[i]))
                    {
                        int alpha_index_upper = plain[i] - 65;
                        int key_index_upper = argv[1][i % key] - 65;
                        printf("%c", (alpha_index_upper + key_index_upper) % 26 + 65);
                    }

                    else if (islower(plain[i]))
                    {
                        int alpha_index_lower = plain[i] - 97;
                        int key_index_lower = argv[1][i % key] - 97;
                        printf("%c", (alpha_index_lower + key_index_lower) % 26 + 97);
                    }
                }

                // All non-alphabetic characters remain the same
                else
                {
                    printf("%c", plain[i]);
                }
            }
        }

        printf("\n");
    }

    else
    {
        printf("Error - Incorrect argument line argument.\n");
        return 1;
    }
}

However, my hello, world! is encrypted as iekmo, wnslc! instead of iekmo, vprke!

And my BaRFoo is encrypted as CaQGoh instead of CaQGon (I passed the test where "BARFOO" is encrypted to "CAQGON" using "BAZ" as keyword)

enter image description here

enter image description here

1 Answer 1

1

CaQGoh instead of CaQGon

This test case is specific for case of letter in plaintext and letter in key not matching. You should ignore the case of the key letter (encrypt the same with keywords "BAZ", "baz" or "BAz"), and preserve the case of the plaintext letter.

iekmo, wnslc! instead of iekmo, vprke!

This test case is specific for advancement within the keyword. You should advance within the key only after encrypting a plaintext letter, non-letters should not change the index within the key. So if you added spaces/punctuation to your plaintext, those would appear in the encrypted text, but not change the encrypted letters behind.

You need a second index you increment only after encrypting a letter, and use that to determine the position within the key.

0

You must log in to answer this question.

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