Having some trouble with pset2 vigenere. Here is my code:

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

int main(int argc, string argv[])
    if (argc != 2)
        // return error if there is an invalid number of arguments
        printf("Error! Ensure there are exactly 2 command line arguments: './caesar' and the key!\n");
        return 1;
        // otherwise continue with the code
        string key = argv[1];

        // get plaintext
        string plaintext = GetString();

        // character length of plaintext variable
        int ptLen = strlen(plaintext);

        int cypherText[ptLen];

        for (int i = 0; i < ptLen; i++)
            // check if letter is part of the alphabet
            if (isalpha(plaintext[i]))
                // check if letter is upper case
                if (isupper(key[i]))
                    // formula for encrypting upper case text
                    cypherText[i] = plaintext[i] + ((key[i] - 65) % 26) ;

                // check if letter is lower case
                if (islower(key[i]))
                    // formula for encrypting lower case text
                    cypherText[i] = plaintext[i] + ((key[i] - 97) % 26) ;
             printf("%c", cypherText[i]);

        return 0;

I know I need to wrap around my key to the plaintext so it repeats itself to the length of the plaintext instead of just encrypting to the length of key once. Ia also need to use a different index for the key. I am very confused. I have thought about how to do this but cannot come to a working solution. Any help on how I could do this is appreciated! Thanks! =D

1 Answer 1


Well, I'll try to push you in the right direction without giving away the store here.

You say that you understand that you need to use a different index for the key and the plaintext, yet you are using i as the same index for both. They absolutely cannot use the same index. The instant you process a non-alpha, the key will go out of synch.

Next, the index for the key should ONLY be incremented when you actually encode a letter, and never when a non-alpha (numbers, punctuation, whitespace, etc.) from the plaintext is processed.

Finally, when you do increment the key index, is it equal to the length of the key? If it is, just reset it to 0. If not, just increment it and move on.

This is very much a case of "KISS, Keep It Simple, Stupid!", an old programming proverb I tell myself at some point on just about every project I work on. Don't overthink it or make it overly complicated. Simple usually means fewer mistakes!

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

You must log in to answer this question.

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