Search code examples
calgorithmvigenerecs50

What's wrong with this vigenere cs50 code?


It just isn't working. Can you point out what's wrong? When I run it I get:

jharvard@appliance (~/Dropbox/pset2): ./vigenere bacon
Meet me at the park
ARTU [R \T aW` ^NaL

Which is clearly wrong. I've spent countless hours on this. here is code:

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

int main(int argc,string argv[])
{
    if(argc!=2)
    {
    printf("Usage: /home/cs50/pset2/caesar <key>\n");
    return 1;
    }
    else
    {
        char *k = argv[1];
        string p = GetString();
        int klen = strlen(k);

        for(int i=0; i<klen;i++)
        {
            if(isupper(k[i]))
            {
                k[i] = k[i]-65;
            }
            else if (islower(k[i]))
            {
                k[i] = k[i]-97;
            }

        }

        for(int i=0, n=strlen(p); i<n;i++)
        {

                if(isupper(p[i]))
                {
                    printf("%c", (((p[i]-65)+(k[i%klen]-65))%26)+65);
                }
                else if (islower(p[i]))
                {
                    printf("%c", (((p[i]-97)+(k[i%klen])-97)%26)+97);
                }

                else
                {
                   printf("%c", p[i]);
                }

        }
        printf("\n");

    }
}

Solution

  • As noted in comments, the code for the loop over p should be :

    EDIT per comment : code is adapted to skip non alpha charactes

    int j = 0
    for(int i=0, n=strlen(p); i<n;i++)
    {
    
            if(isupper(p[i]))
            {
                printf("%c", (((p[i]-65)+(k[j%klen]))%26)+65);
                j += 1
            }
            else if (islower(p[i]))
            {
                printf("%c", (((p[i]-97)+(k[j%klen]))%26)+97);
                j += 1
            }
    
            else
            {
               printf("%c", p[i]);
            }
    }
    

    And the output for ./vigenere bacon with Meet me at the park should be :

    Negh zf av huf pcfx