0

My code seems not able to cipher the text correctly, tried to figure out the problem but failed... Can any help me?

Below is my code, thank you.

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

//Declare variables
string key;
string text;

//check user's input value
int main (int argc, string argv[])
{
    if(argc != 2)
     {
      printf("Please insert ONE key\n");
      return 1;
     }

     for (int i = 0, n = strlen(argv[1]); i < n; i++)
      {
       if(!isalpha(argv[1][i]))
        {
         printf("Please insert an ALPHABETICAL key\n");
         return 1;
        }
      }

    //Get the text
    text = GetString();
    key = argv[1];
    int keylen = strlen(key);
    int p = 0;
    int k = p % keylen;

    //cipher
    for(int j = 0, l = strlen(text); j < l; j++)
    {
     if(isalpha(text[j]))
      {
        p++;

        if(isupper(text[j]))
         {
          printf("%c", ((((text[j] - 'A') + key[k]) % 26) + 'A'));
         }
        else
        printf("%c", ((((text[j] - 'a') + key[k]) % 26) + 'a'));
      }
     else
     printf("%c", text[j]);
    }

    printf("\n");
    return 0;
}
0

They are so many mistakes in this code I am not going to write whole code for you. I will give you some hint to help you to fix these issues

-- First of all you didn't increment key string index along with plain text index. Also need to put condition for key length similar to text length, where ? you have to think for that.

-- You did not decrease ASCII value from each key char value similar to text char.

I hope this will help.

2
  • Thanks for the answer. I changed the cipher code to the following but still don't get the correct output, can you give me more hint please? thank you. printf("%c", ((((text[j] - 'A') + (key[k] - 'A')) % 26) + 'A'));
    – sherman65
    Apr 4 '16 at 12:12
  • Well you forgot that key string can either be upper case or lower case . Apr 5 '16 at 4:44

You must log in to answer this question.

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