I've been having major trouble with Vigenere. I've worked on it every day for the passed two weeks and each day, I solve one problem but encounter another. I was able to get the program with the function definition to work when a single character was entered (ie. int shift char c
) but not when the key involved multiple characters.
I think using pointers is the answer to this but I keep getting pretty confused with the syntax - when should I use * vs & and [ ]. I've watched the content for week 3 and have spent hours googling the topic and I'm still unclear on the matter.
I know there are other problems in my code (such as not cycling through the key again if p > key), but I think I can probably figure them out later. I just want to understand what I'm doing wrong with pointers and defining this function and I'd appreciate any hints to get me going in the right direction. Thanks!!
#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int shift(char* c);
int main(int argc, string argv[2])
{
//Checks that there are only two command-line arguments
if (argc != 2)
{
printf("Usage: ./vigenere key\n");
return 1;
}
int l = strlen(argv[1]);
char* k[l] = (argv[1]);
//Checks that only alpha have been entered
for (int i = 0; i < l; i++)
{
if (isalpha (k[i]) == 0)
{
printf("Usage: ./vigenere key\n");
return 1;
}
}
// implement shift function, store in key
int i = 0;
int* key[i][l] = shift(&k[i][l]);
char* p = get_string("plainttext: ");
printf("ciphertext: ");
//Iterate through p to generate ciphertext
for (int j = 0; j < strlen(p); j++)
{
char c = p[j];
if (isalpha (c) == 1)
{
for (int n = 0; n < strlen(&key); n++)
{
// changes lower case c
if (96 < c && c < 123)
{
printf("%c", (((c - 97) + key[n]) % 26 + 97));
}
// changes upper case c
if (64 < c && c < 91)
{
printf("%c", (((c - 65) + key[n]) % 26 + 65));
}
}
}
//if c != alpha, don't change
else
{
printf("%c", c);
}
}
printf("\n");
return 0;
}
int shift(char* c)
{
// convert c to be A/a = 0 etc
int* k;
if (64 < c && c < 91) // Upper case A == 0, etc
{
k = (c - 65);
}
if (96 < c && c < 123) // Lower case a == 0, etc
{
k = (c - 97);
}
return k;
}