0
    //Iterate over each character in plaintext(i)
int m = strlen(keyword);
for (int i = 0, j = 0, l = strlen(plain); i < l; i++)
{//Iterate over each character in keyword(j) only if plaintext[i] is alphabetic
    if (islower(plain[i]))
    {
        printf("%c", (((plain[i] = plain[i] - 'a') + (keyword[j]%m) % 26) + 'a'));
        j++;
    }
    else if (isupper(plain[i]))
    {
        printf("%c", (((plain[i] = plain[i] - 'A') + (keyword[j]%m) % 26) + 'A'));
        j++;
    }
    else
    {
        printf("%c", plain[i]);
    }
}
printf("\n");
return 0;

Hey, hoping someone can give me some advice. My program compiles but doesn't output the correct cyphertext. For example, an input of 'michael' with a key of ABC results in 'nkchcgn. I think the problem is somewhere within the loop but I can't figure out where.

I tried to read some other common loops problems people had with vigenere and I made sure to track the [i]th character over the plaintext separately from the [j]th character of the keyword. I also made sure to increment [j] only if the plaintext received is alphabetic. I'm not very confident with my use of loops and the modulo function, so I would appreciate any advice.

My full code can be found here

1 Answer 1

1

This:

keyword[j]%m

should be:

keyword[j%m]

Also the assignments shouldn't be inside the printf().

Try:

printf("%c", (((plain[i] - 'A') + (keyword[j%m]) % 26) + 'A'));

There are other ways to make your code faster and better overall, like transforming at the beginning the keyword to its integer representation so you don't have to do keyword[j%m]) % 26 on every iteration.

You can also assign j the value j = (j + 1) % 26 instead of j++ to make sure (even thought it's highly improbable) that it won't overflow, for example if the plaintext had a length larger that what can fit in an int.

2
  • Thanks for the advice, I couldn't figure out why it wasn't wrapping around properly! I have a final small problem. The encyphered output is mostly, but not fully correct. For example, when I use the key 'bacon' as per the problem specifications I get this: $ ./vigenere bacon Plaintext:Meet me at the park at eleven am Cyphertext:Neg zf av uf pcx bt gzrwep oz I think the problem is encyphering using the key character 'o' but I don't know why. If every other character encyphers properly why would this specific character not work? ide.cs50.io/mk3107/ide50#openfile-x
    – MK3107
    Commented Jul 19, 2017 at 12:09
  • In the code you have posted, you transform in the plaintext the character 'A' to 0, by subtracting 'A'. If the key is just the string "ABC", you should also transform the key to [0, 1, 2]. Currently you don't do this.
    – ChrisG
    Commented Jul 19, 2017 at 13:22

You must log in to answer this question.

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