-1

I'm doing the CS50x class and I am stuck at a glitch. I asked them what was going on and no one knew what was going on.

Whenever I try to print a lowercase f it always comes up as ?. Try doing 23 as the argument and abcdefghijklmnopqrstuvwxyz as the input. It's messed up. Here is the code:

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

int main (int argc, string argv[]){
  if(argc !=2){
    return 1;
  }

  string x = GetString();
  int key = atoi(argv[1]);

  for(int a = 0, n = strlen(x); a < n; a++){
    char i = key + x[a];

    if(islower(x[a])){
      if(i > 122){
        i = (i-122) + 96;
      }
    }
    if(isupper(x[a])){
      if(i > 90){
          i = (i-90) + 64;
      }
    }
    printf("%c", i);
  }

  printf("\n");
  return 0;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Jakxna360
  • 857
  • 2
  • 9
  • 31

1 Answers1

3

I suspect it's because your char i defaults to signed. When you add 23 to a lowercase letter, anything that is above 104 (being 127-23) is going to wrap around into negatives. Looking at your code, it will stay negative because it fails the subsequent tests and does not get modified.

It's usually best to do char arithmetic with int, then convert back to char... But you could probably fix this by using unsigned char.

paddy
  • 60,864
  • 6
  • 61
  • 103
  • There's no need to convert back to `char` here at all, since the OP is outputting `i` using the `%c` conversion specifier of `printf()` which takes an `int` as argument. Simply changing the type of `i` to `int` should fix it. – caf Nov 12 '12 at 05:18