0

I am stuck on this problem for days, and I have no idea about where went wrong! When I typed in /vigenere ABC the ciphertext of HELLO just becomes HFN?Z.

PLEASE HELP ME!

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

int main(int argc, string argv[])
{
    //make sure the the key is entered and is 1 word
    if (argc != 2)
    {
        printf("Error. Try Again. \n");
        return 1;
    }

    string key = (argv[1]);

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

    //get plaintext from user
    string text = get_string("Plaintext: ");
    printf("ciphertext: ");

    //create integer for key loop

    for (int i = 0, j = 0, textlen = strlen(text); i < textlen; i++)
    {
        if (isalpha(text[i]))
        {
            //check if each character is lowercase
            if islower(text[i])
            {
                printf("%c", ((((text[i] - 'a') + tolower(key[j]) - 'a') % 26) + 'a'));    
                j++;
            }
            else if (isupper(text[i]))
            {
                printf("%c", ((((text[i] - 'A') + toupper(key[j]) - 'A') % 26) + 'A'));
                j++;
            }
        }
        // returns all non-alphabet value
        else
        {
            printf("%c", text[i]);
        }
    }

    printf("\n");
    return 0;


}

2 Answers 2

0

It seems like the first 3 letters were correctly encoded, but then it falls apart. Using your example of key = "ABC", what happens when j goes past the end of the key, i.e., when j = 3 or 4?

At some point, you need to reuse the key by resetting j to 0.

I'll leave it to you to figure out how to implement that. ;-)

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1
  • Thank you so much! I added another if (j == strlen(key) - 1) loop and solved it!
    – jsyf
    Commented May 9, 2019 at 19:34
0

It looks like you will need to implement a way to handle the situation where the program reaches the end of the keyword ("ABC") but there are still plaintext letters to convert to ciphertext. Remember that in Vigenere's cipher, the keyword is reused if it is shorter than the plaintext (so to encrypt "HELLO", the keyword "ABC" is used as "ABCAB").

You must log in to answer this question.

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