0

So I've been working on pset2 problems with everything going good, until I came across Vigenere cipher. In short it gives me wrong output all the time, any help would be very appreciated!

Here is my code :

char cipher(string text, string key)
{
    for (int i = 0, n = strlen(text); i < n; i++)
    {
    if isalpha(text[i])
    {
      for (int y = 0,l = strlen(key); y < l; y++)
      {
    if (islower(text[i]))
          {
                 printf("%c", ((((char) text[i] +(char) key[i % l]) - 97) % 26) + 97);
          }
    if (isupper(text[i]))
          {
                 printf("%c", ((((char) text[i] +(char) key[i % l]) - 65) % 26) + 65);
          }
    else
          {
                 printf("%c", text[i]);
          }
      } 
    }  
    }
    printf("\n");
    return 0;
}

I'm still new to coding so bear with me ^^
Thanks.

1 Answer 1

1

Two major issues, both common errors. First, what happens in your code when the plain text is upper case and the key is lower case or vice versa? (Try working it out with paper and pencil.)

Second, the code uses the same variable for both the plaintext and the key strings. The problem with that is the plaintext string index is incremented for every char in the string, but the key is only incremented when an alpha is processed and not when an non-alpha is processed. That means that, in this code, when a non-alpha in the plaintext string is processed, the key and the plaintext will be out of synch.

There may be other issues, but these are the big ones. If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1
  • Thank you for pointing this out. Much obliged!
    – Thunder
    Dec 13, 2016 at 20:57

You must log in to answer this question.

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