I am trying to write an encryption code for the Vigenere cipher and I can’t work out what is wrong with my code - I think there is a problem with indexing into the key and wrapping, but I am not sure what:
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int shift(char c);
int main(int argc, string argv[])
{
// Checks to make sure user enters correct number of command-line arguments
if (argc != 2)
{
printf("Usage: ./vigenere keyword\n");
return 1;
}
else
{
// Checks that user has only entered letters as a second command-line argument
for (int i = 0, n = strlen(argv[1]); i < n; i++)
{
if (isalpha(argv[1][i]) == 0)
{
printf("Usage: ./vigenere keyword\n");
return 1;
}
else
{
// Gets plaintext from user
string s = get_string("plaintext: ");
printf("ciphertext: ");
// Converts plain text to cipher text
for (int l = 0, o = strlen(s); l < o; l++)
{
// Get key for this letter
m = shift(s[l] % strlen(argv[1]));
printf("%i\n", m);
if (islower(s[l]))
{
char c = (s[l] + m - 97) % 26 + 97;
printf("%i\n", m);
printf("%c", c);
}
else if (isupper(s[l]))
{
char c = (s[l] + m - 65) % 26 + 65;
printf("%c", c);
}
else
{
printf("%c", s[l]);
}
}
printf("\n");
return 0;
}
}
}
}
int shift(char c)
{
// Converts alphabetical character to a numerical key
if (islower(c))
{
c = c - 97;
}
else
{
c = c - 65;
}
return c;
}