0

I've been banging my head against my keyboard for a while now trying to figure out vigenere.c

I've finally got it really close, but I'm failing just one of the checks when uploading.

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

int main(int argc, string argv[])
{

    if(argc != 2)
    {
        printf("You entered an inccorect number of arguments: enter one argument\n");
        return 1;
    }

    char* key = argv[1];
    int keylen = strlen(key);

    for(int i = 0 ; i < keylen ; i++)
    {
        if(!isalpha(key[i]))
        {
            printf("Your key can only be letters of the alphabet");
            return 1;
        }
    }

    char* text = GetString();


    for(int i = 0, j = 0, n = strlen(text) ; i<n ; i++, j++)
    {
        if(j >= keylen) //Resets j to 0 if j is greater than or equal to the keylength
        {
            j = 0;
        }

        if(!isalpha(text[i])) //If character is not alphabetical, subtract j by 1
        {
            j -= 1;
        }

        if(isupper(text[i]))
        {
            text[i] = ((((text[i] - 65) + (key[j] - 65)) % 26) + 65);
            printf("%c", text[i]);
        }
        else if(islower(text[i]))
        {
            text[i] = ((((text[i] - 97) + (key[j] - 97)) % 26) + 97);
            printf("%c", text[i]);
        }
        else
        {
            printf("%c", text[i]);
        }
    }
    printf("\n");
    return 0;
}

Here is the error I'm getting:

enter image description here

Why is BaRFoo encrypting to CaQGoh (lowercase "H" as the last character) instead of CaQGon when BaZ is the key????

If anyone could offer any insight, I would be very grateful!

1 Answer 1

1

That particular test is designed to check whether the code can handle the cases where the plain text is lower case and the key is upper case or vice versa. It appears that there is nothing in the code to do this. Forget something? ;-)

The code, as written, assumes that the plain text and the key are the same case.

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

1
  • After thinking about your answer for a minute, I got it! Thanks for your help. Turns out I needed to add "else if" conditions for isupper(text[i] && islower(key[j]) and vice-versa. Program works perfectly now!
    – miyun
    Commented Oct 12, 2016 at 23:57

You must log in to answer this question.

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