0

I am currently working on Vigenere. I have the code to where it will work if the key is very short (a few characters), but for some reason my program bums out when the plaintext is long or the key is long. Where could I be going wrong? Thank you all so much and have a great day.

// CS50 Vigenere
// February 19, 2019
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>

// Shift function
int shift(char c);

// Main Function
int main(int argc, string argv[])
{
    // Ensures only one argument that is a string is entered as the key
    if (argc < 2 || argc > 2)
    {
        printf("Error 1: Please enter one argument as the keyword.\nUsage: ./vigenere keyword\n");
        return 1;
    }
    else if (atoi(argv[1]))
    {
        printf("Error 2: Please input a string as the keyword\nUsage: ./vigenere keyword\n");
        return 2;
    }

    // Variables
    string keyword = argv[1];
    int keylen = strlen(keyword);
    int keys[keylen];
    string plaintext = get_string("Plaintext: ");
    int plainlen = strlen(plaintext);
    int j = 0;

    // Finds the keys
    for (int i = 0; i < plainlen; i++)
    {
        if (j == keylen)
        {
            j = 0;
        }
        keys[j] = shift(keyword[j]);
        // Prints the Ciphertext
        char printk = (plaintext[i] + keys[j] % 26);
        printf("%c", printk);
        j++;
    }
    printf("\n");
}

int shift(char c)
{
    if (islower(c))
    {
        return (c - 'a');
    }
    else if (isupper(c))
    {
        return (c - 'A');
    }
    else {
        return 0;
    }
}
2

Apply the %26 to the sum, not the key. Also, don't forget to apply a shift to the plaintext character (like you did in caesar), and shift the result back.

And finally, non-alphabetic plaintext characters are neither encrypted nor do they trigger an increment of j. Just print those like they are.

And a minor detail: Not all not fully alphabetic keywords start with a number. Your atoi won't catch those. Loop over the keyword and check each individual character.

2
  • Thanks for the help so far. When I apply the modulo of 26 to the sum on line 43, for some reason nothing prints at all. Here is what the line looks like: char printk = (plaintext[i] + keys[j]) % 26; Feb 22 '19 at 23:46
  • 1
    Did you do caesar first? You have to do the exact same thing, just that your key changes all the time. The rest, how you handle upper- and lower-case characters, would be the same.
    – Blauelf
    Feb 23 '19 at 9:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .