After banging my head on the desk for the past few days I've decided to post. My problem is with vigenere.c. I figured I had a pretty solid understanding of the algorithm used to create the ciphertext, but when it comes to actually implementing it with a proper loop that follows all the rules I'm at a loss. I'm surprised because I pounded out caesar.c in just a few minutes.
If I'm correct, I'll need to subtract 65 or 97 from both index characters (p[i] and k[j]), modulo by 26, and then add 65 or 97 back again (or p[i] + 'a'/'A'). One place I'm getting confused is how to properly loop through the index of the key. I'm guessing it'll need to be k[j%strlen(p)], but the results I've been getting have varied wildly. At this point my mind's going a little numb and I'm just guessing. My next step is to wipe the whole thing out and start over again.
Ugh...this is the downside of learning Python first--it pretty much does all the hard stuff for you.
Here's what I have so far:
#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if(argc != 2) // Check argc for 2 entries
{
printf("Please enter a single keyword.\n");
return 1;
}
string k = argv[1]; // Our keyword
for (int i = 0, n = strlen(k); i < n; i++)
{
if(!isalpha(k[i])) // Make sure it's alpha only
{
printf("No numbers!\n");
return 1;
}
}
string p = GetString(); // Get the string to be encrypted
int klen = strlen(k);
for (int i = 0, j = 0, n = strlen(p); i < n; i++)
{
if (isblank(p[i]))
{
printf("%c", p[i]);
}
else if (ispunct(p[i]))
{
printf("%c", p[i]);
}
else if (isalpha(p[i]))
{
if (isupper(p[i]))
{
printf("%c", (((p[i] - 'A') + (k[j%klen] - 'A') %26) + 'A'));
j++;
}
else if (islower(p[i]))
{
printf("%c", (((p[i] - 'a') + (k[j%klen] - 'a')%26) + 'a'));
j++;
}
}
else
{
printf("Error in main if/else.\n");
return 1;
}
}
printf("\n");
}