0

My Vigenere cipher is working great, however, once it prints the letters equal to the length of the key, it stops working. Here's my code.

    string key = argv[1];
    int c = 0;
    int keylength = 0;
    int keynum = 0;

    string input = GetString();
    for(int i = 0; i < strlen(input); i++)
    {
        if(isalpha(input[i]))
        {
            if(isupper(input[i]))
            {
                for(c = 0; c < (key[i] - 65); c++)
                {
                    if(input[i] == 'z')
                        input[i] = 'a';
                    else if(input[i] == 'Z')
                        input[i] = 'A';
                    else input[i]++;
                    keylength++;
                    keynum++;
                    if(key[keynum] == strlen(key))
                    {
                        keynum = 0;
                        key[i] = 0;
                    }
                }
            }
            else
            {
                for(c = 0; c < (key[i] - 97); c++)
                {
                    if(input[i] == 'z')
                        input[i] = 'a';
                    else if(input[i] == 'Z')
                        input[i] = 'A';
                    else input[i]++;
                    keylength++;
                    keynum++;
                    if(key[keynum] == strlen(key))
                    {
                        keynum = 0;
                        key[i] = 0;
                    }
                }
            }
        }
        else
        {
        }
    }
    printf("%s\n", input);

Here's the check50 for examples.

:) encrypts "a" as "a" using "a" as keyword
:( encrypts "world, say hello!" as "xoqmd, rby gflkp!" using "baz" as keyword
   \ expected output, but not "xoqld, say imylp!\n"
:( encrypts "BaRFoo" as "CaQGon" using "BaZ" as keyword
   \ expected output, but not "CaQFoo\n"
:( encrypts "BARFOO" as "CAQGON" using "BAZ" as keyword
   \ expected output, but not "CAQFGV\n"

It encrypts the first three letters, but then doesn't work anymore. I spent a few hours trying to get it to loop back to the beginning of the key, but nothing worked. Do you have any idea how to go about fixing this?

1

You loop back to the beginning of the key using the modulo operator and the length of the key. Something along the lines of key[i % strlen(key)]

You must log in to answer this question.

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