Jakxna360 Jakxna360 - 3 months ago 21
C Question

Islower function glitch

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;
}

Answer

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.