I have an application that prompt to user an character from user:
char letter;
printf("Letter:\n");
scanf("%s", &letter);
printf("ASCII code = %d\n", letter);
The problem is the accent that the user can write. if input is Á the code above given ASCII code = -61 then I thought, if I turn it in an positive number, I get 61 that is A in ASCII. printf("ASCII code = %d val = %c\n", letter, abs(letter));
but it does not works as expected, it given ASCII code = -61 val =
instead of A why?
Áhas character code 193 in ASCII.The range of a
charis -128 to 127. The range ofunsigned charis 0 to 255.The problem with your code is that you’re working with a signed char instead of an unsigned char. When you output the signed char, it will sign extend
letterto an integer and output it. If you use the unsigned variant you’ll get the correct output.