0

My Vigenere code is printing incorrectly. I can't pinpoint the source of it, but here's my code.

    int main(int argc, char *argv[])
    {
        if(argc < 2)
        {
            printf("waoh mahn!\n");
            return(1);
        }
        else if(argc > 2)
        {
            printf("waoh mahn!\n");
            return(1);
        }

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

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

Here's the check50

:) vigenere.c exists
:) vigenere.c compiles
:( encrypts "a" as "a" using "a" as keyword
   \ expected output, but not "t\n"
:( encrypts "world, say hello!" as "xoqmd, rby gflkp!" using "baz" as keyword
   \ expected output, but not "qhjli, qyh bfrgi!\n"
:( encrypts "BaRFoo" as "CaQGon" using "BaZ" as keyword
   \ expected output, but not "PtDFti\n"
:( encrypts "BARFOO" as "CAQGON" using "BAZ" as keyword
   \ expected output, but not "PNDFTI\n"
:) handles lack of argv[1]
:) handles argc > 2
:( rejects "Hax0r2" as keyword
   \ expected output, not a prompt for input

Any idea how I might go about having it print correctly?

1 Answer 1

1

Let's take the first test encrypts "a" as "a" using "a" as keyword for a spin through the code.

  1. key="a" (as defined by the test)
  2. input = "a" (as defined by the test)
  3. We will do this loop for(int i = 0; i < strlen(input); i++) one time, since strlen("a") is 1.
  4. This if(isalpha(input[i])) evaluates to true, since input[0] is 'a'.
  5. This loop for(c = 0; c < key[i]; c++) will execute 97 times. Why is that? key[i] = 'a', ascii a is 97.
  6. The first 26 iterations will add 1 to input[0], end up at 'z', and wrap back to 'a' if(input[i] == 'z') {input[i] = 'a';}
  7. The next 26 iterations will add 1 to input[0], end up at 'z', and wrap back to 'a' if(input[i] == 'z') {input[i] = 'a';}
  8. The next 26 iterations will add 1 to input[0], end up at 'z', and wrap back to 'a' if(input[i] == 'z') {input[i] = 'a';}
  9. The last 19 iterations will add 1 to input[0] and end up at 't'.

You should see now that this is not doing what the assignment requires. You need to review the course material. Maybe start with ASCII and Vigenère Cipher. You may find an ascii table helpful as well (there are many on line). It may also help to encode something on a piece of paper. See how you do it, then tell the computer to do it the same way! :)

You must log in to answer this question.

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