0

Below is my vigenere code for enciphering text, but the enciphering key does not wraparound.

/* a program, vigenere, that encrypts messages using Vigenere’s cipher*/

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

int main(int argc, string argv[])
{
    //Checks for the required argc
    if(argc != 2)
    {
        printf("Command line argument error, please insert key!\n");
        return 1;
    }

    for(int i = 0, n = strlen(argv[1]); i < n; i++)
    {
        if(isalpha(argv[1][i]) == 0)
        {
            printf("key argv[1] has to be alphabetic\n");
            return 1;
        }
    }
    //Prompts user for input of plaintext
    char* Plain_text = get_string();
    for(int i = 0, m = strlen(Plain_text); i < m; i++)
    {
        //Checks if plaintext is alphabetic
                if(isalpha(Plain_text[i]))
                {
                    if(isupper(Plain_text[i]))
                    {
                            argv[1][i] = ((argv[1][i] - 'A'));

                            //Alphabetic wraparound for upper case letters
                            Plain_text[i] = ((Plain_text[i] - 'A') + argv[1][i]) % 26;
                            printf("%c", Plain_text[i] + 'A');
                    }
                    else
                    {
                        argv[1][i] = ((argv[1][i] - 'a'));
                        //Alphabetic wraparound for lower case letters
                        Plain_text[i] = ((Plain_text[i] - 'a') + argv[1][i]) % 26;
                        printf("%c", Plain_text[i] + 'a');
                    }
                }
                else
                printf("%c", Plain_text[i]);
    }
    return 0;
}

can anyone help me point out what i did wrong?.Thanks

0

If the key is BAZ (length 5, indexes 0 - 2) and the plain text is "world, say hello!" (length 17, indexes 0 - 16), what happens in the second i loop when i is 4? It's going to calculate the "shift" based on argv[1][4]. What? There is no argv[1][4]!!! Generally, you cannot use the same subscript for the key and the plain text for just this reason (plus, you don't "use" a key index if the plain text is not an alpha).

Another problem, though not with "wrapping", is here argv[1][i] = ((argv[1][i] - 'A'));. This will only work if the case of the key is the same as the case of the plain text. That is not always so. (Think about the example when index is 0).

There may be other problems in the calculations that will require tweaking once you conquer the "wrapping" problem. But correcting these problems should get you on the path the success.

You must log in to answer this question.

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