0

This is my code:

**#include

include

include

include

include

int main(int argc, string argv[]) { if (argc != 2) { printf("You should have two command line arguments!\n"); exit(0); }

int kl = strlen(argv[1]);

printf("Please input a message: \n");
string s = GetString();


for (int i = 0, n = strlen(s), j = 0; i < n; i++, j++)
    {

        if ( isalpha(s[i]))
            {
                if (isupper(s[i]) && isupper(argv[1][j]))
                    {
                        printf("%c", (((s[i] - 65) + (argv[1][j % kl] - 65)) % 26) + 65 );
                    }



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



                else if (islower(s[i]) && islower(argv[1][j]))
                {
                    printf("%c", (((s[i] - 97) + (argv[1][j % kl] - 97)) % 26) + 97);
                }

                else //lower plaintext char, uppercase key char
                {
                    printf("%c", (((s[i] - 97) + (argv[1][j % kl] - 65)) % 26) + 97);
                }
            }

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




    }


printf("\n");

}**

The command line argument I'm using for the key is "AbCd". As for the plaintext, I write "AbCd ABCD abcd AbCd"

The answer I get, unfortunately is

AcEg [IEM aiem AiEm

I'm not too sure why the 'A' in the second block is becoming a '[' or the 'B' and 'b' in the second and third blocks becoming 'i'.

Any help is appreciated. Thank you!

2

There's a small mistake in the elseif statement under if condition -

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

(Just replace j with j%kl)

Edit : I found another mistake. Note that, while checking whether the character in your key is in uppercase or in lowercase, you are using argv[1][j]. Instead you must use argv[1][j%kl]. Otherwise it will go out of the range of valid indices as j increases.

Do hit the tick button beside the answer, if it works!

| improve this answer | |
  • Thanks for your help, but unfortunately it didn't fix things. – Manuel Stoilov Jun 27 '16 at 16:59
  • I have made an edit. Hope that it works now. – abhishek Jun 27 '16 at 18:58
  • Got it! As you said, simply had to replace the j's with j%kl. Thanks mate! – Manuel Stoilov Jun 28 '16 at 14:40

You must log in to answer this question.

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