cs50 vigenere - loops incorrectly

58 Views Asked by At

Apologies if the answer to this is incredibly simple. I just can't work it out.

I've been working on the CS50 Vigenere problem and I think I'm almost there. However the program loops in a way that I don't expect and I'm not sure why. Once it has printed the first ciphered character of the plaintext, it loops back to move to the next character in the key but misses out the part where it needs to move to the next character of the plain text. At least I think that is what is happening.

Here is my code. Any help would be greatly appreciated.

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

int main(int argc, string argv [])
{
    int a;
    int ciphertext;
    int k;
    string plain;
    int cipher;
// check user has input a  valid number of arguments

    if (argc < 2 || argc > 2)
    {
        printf("please input a valid number of arguments\n");

        return 1;
    }
// check user has input a valid key and prompt for plaintext
    char * key = argv [1];


        for (a = 0; a < strlen(key); a++)
        if (!isalpha(key[a]))
        {
            printf("Please input a valid key. Key must be alphabetical");
            return 1;
        }



{
    if (a == strlen(key))
    {
        plain = get_string("Plaintext: ");
    }
{
    printf("ciphertext: ");
}
}


//read plaintext and keep track
{
    for (int i = 0, n = strlen(plain); i < n; i++)
    {
//read key and keep track
        if (isalpha(plain[i]))
        {
            for (int j = 0, p = strlen(key); j < p; j++)



//convert key to numerical

            {
                if (isupper(key[j]) > 'A')
                {
                    k = (key[j] - 65);
//calculate ciphertext and print (upper case)
                    {
                        printf("%c", (plain[i] + (k % p) %26) +65);
                    }
                }

            else if (islower(key[j]) > 'a')
            {
                k = (key[j] - 97);
                {
                    printf("%c", (plain[i] + (k % p) %26) +97);
                }
            }
            else printf("%c", plain[i]);


        }
    }
    }



    {
        printf("\n");
    }

}


}
0

There are 0 best solutions below