My vigenere code is compiling and executing; however, despite the wrap-around functionality working, whatever I type seems to shift an extra 13 letters to the right:
Plaintext: ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz
Ciphertext: NOPQRSTUVWXYZABCDEFGHIJKLM nopqrstuvwxyzabcdefghijklm
Using 'e' (ascii value 101) as example plaintext with a cipher of 'A' (so, 0), the function should execute:
if (islower(plaintext[c]))
{
int f = plaintext[c] - 'a';
plaintext[c] = ((f + input[e]) % 26) + 'a';
}
if (islower(plaintext[c]))
{
int f = 101 - 97;
plaintext[c] = ((4 + 0) % 26) + 97;
}
which should equal 4 + 97, or 101, returning 'e' again, yet doesn't. I've tried the debugger a few times, and haven't been able to come up with a reason why this is happening.
Many thanks in advance for help!
Full code:
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int main (int argc, string argv[])
{
if (argc < 2 || argc > 2)
{
printf("Invalid input. Usage: './vigenere k'\n");
return 0;
}
else
{
string input = argv[1];
int h = strlen(input);
for (int a = 0, b = strlen(input); a < b; a++)
{
if (isalpha(input[a]))
{
continue;
}
else
{
printf("Your key must consist of only letters\n");
return 0;
}
}
string plaintext = get_string("Plaintext: ");
printf("Ciphertext: ");
for (int d = strlen(plaintext), c = 0; c < d; c++)
{
int e = (c % h);
if (isalpha(plaintext[c]))
{
if (islower(plaintext[c]))
{
int f = plaintext[c] - 'a';
plaintext[c] = ((f + input[e]) % 26) + 'a';
}
else
{
int g = plaintext[c] - 'A';
plaintext[c] = ((g + input[e]) % 26) + 'A';
}
printf("%c", plaintext[c]);
}
else
{
printf("%c", plaintext[c]);
}
}
printf("\n");
}
}