Help me please with a problem on coding vigenere.c.
The problem is with figuring out the correct code for using the key-formula on the plaintext.
I think that i've found out the correct formula for the key with chars loop. The concept is that when the char counter reaches the length of the string argv[1] it starts from [0] char again. I've tested this with printf and it worked correctly. The formula i use is:
j = (strlen(k) - i) % (strlen(k))
But, unfortunately, i cannot find out how to apply this in a correct way for crypting the plaintext message. When i crypt, i get it crypted but definitely not the way it should be.
My full code is below. Please don't make the correct code for me. I just need an advise. Thank you in advance.
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int main(int argc, string argv[])
{
if (argc != 2)
{
printf("The key is not correct\n");
return 1;
}
for (int i = 0; i < strlen(argv[1]); i++)
{
if (!isalpha(argv[1][i]))
{
printf("The key is not correct\n");
return 1;
}
}
string p = GetString();
int n = strlen(p);
string k = argv[1];
int j = 0;
for (int i = 0; i < n; i++)
{
// Declare conditions for usage of the key
if (isalpha(p[i]))
{
if (i < strlen(k))
{
j = i;
}
else if (i >= strlen(k))
{
j = (strlen(k) - i) % (strlen(k));
}
if (isupper(k[j]))
{
k[j] -= 'A';
}
else if (islower(k[j]))
{
k[j] -= 'a';
}
}
// Crypt chars for lowercase letters
if (islower(p[i]))
{
p[i] = (p[i] - 'a' + k[j]) % 26 +'a';
}
// Crypt chars for upper case letters
else if (isupper(p[i]))
{
p[i] = (p[i] - 'A' + k[j]) % 26 + 'A';
}
}
// Print the crypted message
printf("%s\n", p);
return 0;
}