0

I'm going through Vigenere right now, but I've run into 2 issues:

  1. I can't seem to get my key to skip over spaces in the plaintext. I assigned two separate indices (i and j), but it seems to try to shift the space by "x[j] spaces. For example, if I set the key to "abc", and then enter in the plaintext "aaa aa" , it will give me "abc bc" instead of "abc ab".

  2. When I run the program, it runs the program as many times as there are characters in the key, and then prompts for another plaintext right away.. For example:

~/workspace/pset2/vigenere/ $ ./vigenere abc plaintext: aa ciphertext: abplaintext: a ciphertext: aplaintext: aaa aa ciphertext: abc bc

Here is my code:

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

int main(int argc, string argv[])

{
if (argc < 2)

{
    printf("Make sure you type in something!\n");
    return 1;
}

if (argc > 2)

{
    printf("Make sure you only enter 1 argument!\n");
    return 1;
}

string x = argv[1];
int len_x = strlen(x);

for (int k = 0; k < len_x; k++)
{
    if(!isalpha(x[k]))
    {
        printf("Make sure you only enter letters!\n");
        return 1;
    }

string s = get_string("plaintext: ");
int len_s = strlen(s);
printf("ciphertext: ");

    for (int i = 0, j = 0; i < len_s; i++, j++)
    {

        if (j == len_x)
        {
            j = 0;
        }

        if (islower(s[i]) && islower(x[j]))
        {
            printf("%c", ((((s[i] + (x[j]- 97)) - 97) % 26) + 97));
        }
        else if (islower(s[i]) && isupper(x[j]))
        {
            printf("%c", ((((s[i] + (x[j]- 65)) - 97) % 26) + 97));
        }
        else if (isupper(s[i]) && islower(x[j]))
        {
            printf("%c", ((((s[i] + (x[j] - 97)) - 65) % 26) + 65));
        }
        else if (isupper(s[i]) && isupper(x[j]))
        {
            printf("%c", ((((s[i] + (x[j] - 65)) - 65) % 26) + 65));
        }

         else
        {
            printf("%c", s[i]);
        }
    }

}

printf("\n");

}

1 Answer 1

0

The code reprompts for plaintext because the closing curly brace for the for loop that checks that the key is all alpha was incorrectly placed near the end of the program. The remaining code of the program has been nested inside that loop as a result.

The spaces (and all non-alphas) are "not being skipped over" because the index for the key, j, is being incremented for every char, because it is incremented as part of the for loop setup. J should ONLY be incremented when a letter is processed, and NEVER incremented when a non-alpha is processed. It should not be part of the for loop setup.

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 .