0

I am having some trouble with Caesar. I am able to determine whether or not the character is an uppercase or lowercase but I cannot get the formula to convert to the numeric index(then back to ASCII again) that Zamyla mentioned in her walkthrough just right. Could someone give me a hint or pointer that would get me across the finish line on this one please? Here's my code:

{
int key = atoi(argv[1]);

if(argc != 2){

    printf("Invalid entry. Your first argument must be a number.");
    return 1;
}

string plainText = GetString();
int textLength = strlen(plainText);
//string ciperText;

for(int i = 0, n = textLength; i <= n; i++)
{

      if(isalpha(plainText[i]))
      {
          if(isupper(plainText[i]))
          {
              printf("%c", (plainText[i] + key%26)); 
          }
          else if(islower(plainText[i]))
          {
              printf("%c", (plainText[i] + key%26)); 
          }
      }

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

}

0

Your problem isn't in converting char to int, you're already doing it with atoi(). Look at your encryption algorithm, use a pen and paper to see if you're getting what you're supposed to be getting.

1
  • (plainText[i] + key%26) seems slightly off. I think you need a bracket separating plainText[i] + key AND %26. You also need to subtract 65 from plaintext[I] so that it is in the 0 to 25 range rather than the 65 to 91 range. So for example if we have the character y in as our first subject of the input message, it will change to 90, we then subtract 65 to get 25 and then we add the key (lets assume key = 5), giving us 30, and then this is subject to %26 which results in the value 4, now we convert back from the 0 - 25 TO ASCII by adding the 65 back and then we call (char)(4 + 65) – Bijan Khadembashi Aug 30 '16 at 7:39
0

I struggled with this one when I did it aswell.

(plainText[i] + key%26) seems slightly off. I think you need a bracket separating plainText[i] + key AND %26.

You also need to subtract 65 from plaintext[I] so that it is in the 0 to 25 range rather than the 65 to 91 range.

So for example

1 if we have the character y in as our first subject of the input message, it will change to 90
2 we then subtract 65 to get 25
3 then we add the key (lets assume key = 5), giving us 30
4 then this is subject to %26 which results in the value 4,
5 now we convert back from the 0 - 25 TO ASCII by adding the 65 back
6 then we call (char)(4 + 65) to give us the character (it will be lower)
0

Update: Thanks for everyone's help on this one. I managed to figure it out after whitebaording the problem. Whilst I cannot share the exact formula it required me using the decimal ASCII value for A more than once in the formula.

Then of course, doing a little bit of tweaking to cater for lowercase characters.

You must log in to answer this question.

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