I have been banging my head as to why when I run vigenere with bacon argument, Meet me at the.....etc, never turns out the same as on the CS50 page, but always the same encryption values on my side. However, my letters are encrypting through the key and case is being kept as input by the user.
After spending hours trying to modify and change my code, I just counted the letters to encryption and realised my cipher is adding an extra 19 places on the key index? I have no clue why.
I modified my cipher to subtract the 19 and it works. I have run various tests and multiple variations and my cipher seems to work correctly each time. My question is, where on earth did this 19 come from?
Thanks in advance.
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int cipher(int i, char k);
int main(int argc, string argv[])
{
if (argc != 2)
{
printf("Usage: ./vigenere (key alphabetical only)\n");
return 1;
}
for (int i = 0, n = strlen(argv[1]); i < n; i++)
{
if (!isalpha(argv[1][i]))
{
printf("Usage: ./vigenere (key alphabetical only)\n");
return 1;
}
}
string s = GetString();
string key = argv[1];
int kl = strlen(key);
int k = 0;
for (int i = 0, n = strlen(s); i < n; i++)
{
if (isalpha(s[i]))
{
printf("%c", cipher(s[i], key[k%kl]));
k++;
}
else
printf("%c", s[i]);
}
printf("\n");
return 0;
}
int cipher(int c, char k)
{
if (islower(c)) return (c -'a' + k - 19) % 26 + 'a';
if (isupper(c)) return (c -'A' + k - 19) % 26 + 'A';
return c;
}