0

i am attempting Vigenere on CS50 Pset2.

I am creating a new array with same length as keyword to shift to its digit counterpart.

However i am not getting the correct answer, any idea what is the issue?

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

void printError();
int checkWord();
string plainToCipher();

int main(int argc, string argv[])
{
    //Count Command-Line Arguments
    if(argc != 2)
    {
        printError();
        return 1;
    }

    //Validate key is keyword
    else if(checkWord(argv[1]))
    {
        printError();
        return 2;
    }

    //Shift Plaintext into Ciphertext

    else
    {
        string plainText = get_string("plaintext: ");
        string cipherText = plainToCipher( plainText, argv[1] );
        printf("ciphertext: %s\n",cipherText);
        return 0;
    }
}

//Error Function
void printError()
{
    printf("Usage: ./vigenere keyword \n");
}
//Check Int Function, 1 if not Word, 0 if Word
int checkWord(string check)
{
    int i = strlen(check);
    int k = 0;

    do
    {
        if( check[k] < 'A' || (check[k] > 'Z' && check[k] < 'a') || check[k] > 'z' )
        {
            return 1;
        }
        else
            k++;
    }while (k<i);

    return 0;
}
//Ciphering Function
string plainToCipher(string plainText,string keyword)
{

    int i = strlen(plainText);
    int k = strlen(keyword); //used for modular cycle
    int i1 = 0;




    char newstring[k];
    //shifts keyword string to its digit counterpart
    do
    {
        if(keyword[i1]>='a') 
        {
            newstring[i1] = keyword [i1] - 'a';
        }

        else
        {
            newstring[i1] = keyword[i1] - 'A';
            printf("%c", newstring[i1]);
        }

    i1++;
    }while(i1<k);

    int j = 0;

    do
    {

            if(plainText[j] >= 'a' && plainText[j] <= 'z')
            {
                plainText[j] = ((plainText[j] - 'a') + ( (newstring[j%k]-'0') )) % 26 + 'a'; 
            }

            else if(plainText[j] >= 'A' && plainText[j] <= 'Z')
            {
                plainText[j] = ((plainText[j] - 'A') + ( (newstring[j%k]-'0') )) % 26 + 'A';
            }
    j++;

    }while(j<i);

    return plainText;

}

My Answer is :

~/ $ ./vigenere abc
plaintext: HELLO
ciphertext: 2086:

And this is wrong.

1

The -'0' makes no sense, since we are talking about value 0, not character '0'. You already mapped keyword characters 'A'..'Z' and 'a'..'z' to 0..25.

Please note that you can't derive the index within the keyword directly from the index within the plaintext. Non-alphabetic characters do not cause the index within the keyword to advance. Create a second index, starting at 0, and advance it only on encrypting a letter, not on skipping a non-letter.

You must log in to answer this question.

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