Please help me with my code below. I cannot seem to get the argv[1] (the key) to loop around plaintext. For example, if I my key is "bacon", and the plaintext is "Meet me at the park", I only get "Negh z". I tried to use modulo to loop, e.g., k % strlen(argv[1]), but that does not seem to work.

Here is part of my code: (I excluded the parts for lowercase k, uppercase n, and for spaces)

for (int i = 0, n =0; n < strlen(plaintext); n++)
    char k = argv[1][i];

    //for uppercase k
    if (isupper(k))

            //for lowercase n
                printf("%c", ((((plaintext[n] - 'a') + k) % 26) + 'a'));

First of all it might be better for you if you assigned argv[1] to a string variable called keyphrase for example:

char* keyphrase = argv[1];

Now say keyphrase is "bacon". It would be like that:

  • keyphrase[0] == 'b'
  • keyphrase[1] == 'a'
  • keyphrase[2] == 'c'
  • keyphrase[3] == 'o'
  • keyphrase[4] == 'n'
  • keyphrase[5] == '\0'

and if you do

int length = strlen(keyphrase);

length would be 5.

So let's go through the loop you have to go:

  • i == 0, k should be keyphrase[0]
  • i == 1, k should be keyphrase[1]
  • i == 2, k should be keyphrase[2]
  • i == 3, k should be keyphrase[3]
  • i == 4, k should be keyphrase[4]
  • i == 5, k should be keyphrase[0]
  • i == 6, k should be keyphrase[1]
  • ... and so on.

So see that you should somehow use the modulo operator on the index of keyphrase and assign that to k. You shouldn't use the modulo on k itself.

I think this should get you going. If not, or if I've confused you more, leave a comment below. On the other hand, if this answers your question please accept it by clicking the gray check-mark to the left, so that it becomes green. You can also vote it up by pressing the up arrow above the check-mark. And don't forget to keep coding!

You must log in to answer this question.

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