I am currently working on Vigenere, and for whatever reason my key values are running through randomly and just not working. I'm new to programming, so sorry if I am missing something major in my code or if the format of the question is wrong. Here is my Vigenere code:

// 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);

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

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

1 Answer 1


The code is using a pair of nested for loops. The outer loop cycles through the plaintext while the inner loop cycles through the key. That means that for EACH char in the plaintext, the inner loop will cycle through the entire key. This is a major structural error.

As each char in the plaintext is processed, the code should only process at most one char from the key. It should not loop through the entire key. Further, a char in the key should ONLY be consumed when an alpha is processed from the plaintext. That means that when the char from the plaintext is NOT an alpha, nothing should be consumed from the key. To do this, the key should have it's own index variable and that var should only be incremented when a key char is consumed - never by a for loop.

There may be more issues, but those would be for a new question.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

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