0

it's not printing what i expecting when i write (b) as key and (m) as plaintext for checking it prints (n) but more than expected and i don't know what i'm missing any help would be appreciated, here's my code :

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

int shift(char c);

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

    if (argc != 2)
    {

        printf("Usage: ./vigenere keyword\n");
        return 1;
    }
    for (int i = 0, n = strlen(argv[1]); i < n; i++)
    {

        if (!isalpha(argv[1][i]))
        {

            printf("Usage: ./vigenere keyword\n");
            return 1;
        }
    }

    string plaintext = get_string("plaintext: ");

    if (plaintext == NULL)
    {

        printf("please provide an input to cipher\n");
        return 1;
    }

    printf("ciphertext: ");

    int key = strlen(argv[1]);

    int s = strlen(plaintext);

    for (int i = 0; i < key; i++)
    {

        if (argv[1][i] == '\0')
        {

            i = 0;
        }
        for(int j = 0; j < s; j++)
        {

            if (isalpha(plaintext[j]))
            {

                printf("%c", (((plaintext[j] + shift(argv[1][i]) % key))));
            }
            else
            {

                printf("%c", plaintext[j]);
            }
        }
    }

    printf("\n");
}

int shift(char c)

{

    if (isupper(c))
    {
        return c - 65;   
    }
    return c - 97;
}
0

You've made a somewhat common error in your design. The code is using two nested for loops to go through the key and the plaintext. That means that it's going to process the inner loop code i * j times!

The code should loop through the plaintext code using a for loop, but should consume the characters in the key string only as needed, and not in a loop. Remember, the key chars are only consumed/used for alphas in the plain text and never for non-alphas.

As for your formula for encoding, that's an entire different issue. Let me suggest going back and watching the shorts that cover encoding.

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 .