0

I'm stuck on pset2 Vigenère for a couple of days now. What's left for me to do is the wrap around. A recent draft of the below program compiled and worked fine if the length of the plaintext was equal to the length of the key, which is still far from the desired outcome, I assume...

I realized that I had to implement a second counter (j) to iterate over the keyword. However, I can't quite wrap my head around of how the counter is supposed to work.

Any help would be much appreciated!

#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

int shift(char c);

int main(int argc, string argv[])
{
    //Check that program was run with one command-line argument
    if (argc == 2)
    {
        //Iterate over the provided argument to check if all characters are             alphabetic
        for (int i = 0, n = strlen(argv[1]); i < n; i++)
        {
            if (!isalpha(argv[1][i]))
            {
                printf("Usage: ./vigenere keyword\n");
                return 1;
            }
        }

    //Prompt user for plaintext
    string pt = get_string("plaintext: ");
    printf("ciphertext: ");

    int keylen = strlen(argv[1]);
    //Iterate over each character of the plaintext
    for (int i = 0, j = 0, n = strlen(pt); i < n; i++)
    {
        int key = shift(argv[1][j]);
        //If it is an uppercase letter, rotate it, preserving case, then               print out the rotated character
        if (islower(pt[i]))
        {
            printf("%c", (((pt[i] + key[j % keylen] - 97) % 26) + 97));
        }    
        //If it is a lowercase letter, rotate it, preserving case, then                 print out the rotated character
        else if (isupper(pt[i]))
        {
            printf("%c", (((pt[i] + key[j % keylen]) - 65) % 26) + 65));
        }
        //If it is neither, print out the character as is
        else
        {
           printf("%c", pt[i]);  
        }
    }
    {
        printf("\n");
        return 0;
    }
    }
}

int shift(char c)
{
    if (islower(c))
    {
        return c - 97;
    }
    else
    {
        return c - 65;
    }
}


0

Mostly fine, I think. The % keylen should go into the argv[1][j], key is an integer and cannot be subscripted, so use key, not key[j % keylen]. Also missing is that you have to increment j whenever you encrypt a letter (but not on printing a non-encrypted character, for example punctuation).

And you don't have output for the wrong argc, I think you are meant to complain print usage instructions in that case as well.

You must log in to answer this question.

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