1

I've got my code to cycle through the plaintext index p and the key index. However I keep getting an error when I am printing and can't figure it out. When I use the test spec using bacon as the key and "Meet me at" for string p. instead of getting "Negh zf av" I get "Negh z gb" where it is deleting a character. It is must not be cycling through the key index properly as it is moving 2 places however I cant understand why a char is being removed.

Appreciate any kind help

{

string key = argv[1];


string p = GetString();

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

if (isupper(p[i]))
    {


        if (isupper(key[j]))
         {

            int k = (key[j % strlen(key)] - 65) % 26;
            char ciph = ((p[i]- 65 + k) % 26) + 65;
            printf("%c", ciph);

         }
        if (islower(key[j]))
        {
            int k = (key[j % strlen(key)] - 97) % 26;
            char ciph = ((p[i]- 65 + k) % 26) + 65;
            printf("%c", ciph);

        }
     }  

 if (islower(p[i]))
 {

    if (isupper(key[j]))
      {

        int m = (key[j % strlen(key)] - 65) % 26;
        char ciph = ((p[i]- 97 + m) % 26) + 97;
        printf("%c", ciph);

      }
    if (islower(key[j]))
    {
        int m = (key[j % strlen(key)] - 97) % 26;
        char ciph = ((p[i]- 97 + m) % 26) + 97;
        printf("%c", ciph);

    }    
 }
if (isalpha(p[i]))
j++;

else 
{
printf("%c", p[i]);
}


}
1
  • Look at your condition checks using key. Commented Jul 10, 2015 at 0:24

1 Answer 1

0

Skimming through, I don't see where you are resetting your cypher counter. You'll need to find a way to cycle back to the first letter of the cypher key in case the cypher key is shorter than the plain text to be encoded.

2
  • Won't {int k = (key[j % strlen(key)] - 65) % 26;} and etc cycle through the cypher key, and { if (isalpha(p[i])) j++; } only increase the count of key[j] on alpha plaintext? Commented Jul 9, 2015 at 16:56
  • @lyflonglerner this is not an answer and should probably be posted as a comment to the question.
    – ChrisG
    Commented Jul 9, 2015 at 22:24

You must log in to answer this question.

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