0

Can someone please point me in the right direction to correct this code? i am getting blank results when entering a lowercase letter. Thanks!

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


int main(int argc, string argv[])


{

  if (argc ==1)
    {     
    //say this if no arguments if entered//
    printf("ENTER A KEY!!\n");
    }

  else {  
 string p = get_string();

 //changes key to integer//
int key = atoi(argv[1]);
int cipher;  

  for (int i = 0; i<strlen(p); i++)
    {
      int chr = p[i];

      if (isupper(chr))
        {
            cipher = ((chr-65+key) % 26)+65;
            printf("%c", cipher);
        }

       else {

      printf("%c", cipher = (chr+key) % 26);
       }

}

 return 0;

}
}
1

cipher = (chr+key) % 26

So, if you enter, say d and a key of 5, then:

cipher = ('d' + 5) % 26
cipher = (100 + 5) % 26
cipher = 1

1 is a non printable char.

The formula for caesar given in the pset works on the assumption that your chars are in the range of 0 - 25 (not the ascii value). So you need to bring your 'd' down to that range (perhaps by subtracting 'a' from it?), do your calculation, then bring it back up to the ascii range by adding 'a' back. Then you'd have something like:

('d'-'a' + 5) %26 + 'a'
(100 - 97 + 5) %26 + 97
 8 + 97
 105 which would print 'i' as you'd expect.

You've done that for your uppercase chars; not sure why you didn't for your lowercase ones.

0

I can't believe i missed something like that, starred at this for quite some time and it was something simple in the end. Oh well, on to the next problem!

Thank you

You must log in to answer this question.

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