I'm stuck halfway in vigenere. This is some of my code.
When I tried to work that out, something went wrong.
Kindly appreciate any help.
CS50 Stack Exchange is a question and answer site for students of Harvard University's CS50. It only takes a minute to sign up.Sign up to join this community
You shouldn't consume any characters from
key if the current character in
text in non-alphabetical character. The variable
i increases anyway whether the current character in
text is alphabetical or not. Maybe you should calculate the index of the current character in
key using a different separate variable.
Edit 0: given the string "Meet me at the park at eleven am" as
text and the keyword "bacon" as
key, here's how
key should repeat
Meet me at the park at eleven am baco nb ac onb acon ba conbac on
Meet me at the park at eleven am baconbaconbaconbaconbaconbaconba
Edit 1: After debugging your code, it turns out you have 2 main issues
you should be having this loop
for (int j = 0 ; j < k ; j++)
because we don't really need to iterate
k times each time we encrypt an alphabetical
j should be declared separately maybe in the header of the main
for loop like that
for (int i = 0, j = 0 ; i < n ; i++ )
Also, keep in mind that
j should be incremented by 1 if and only if an alphabetical
text is encrypted.
we really shouldn't use
key[i] here because
i is incremented anyway and it doesn't represent the index of the current key at all. Also,
i itself might be beyond the array (i.e., the string
key) boundaries at this moment if the plaintext is longer than the
key. And that's what caused the
"abcdef" to get encrypted to
"ln" respectively instead of
key as we expected because
key[i] is a garbage value. Since
isupper() checks a garbage value in this case which happens to be an ASCII value of an uppercase character, this makes the wrong condition gets executed.
To fix that, simply, check
key[j % k] instead of
Hope that helps!