0

I am working in a C/C++ code that casts a char to its integer value and then needs to print it back to its char value.

But, when I try to print an "Extended ASCII" character using the printf function, it shows a different character and I can't figure out what's wrong.

int charInt = (int) 'á'; // -31
char casted = (char) charInt;
printf("%c\n", casted); // ß

If I debug the code (I'm using Visual Studio 2017), the variable 'casted' shows the correct 'á' value in IntelliSense.

I tested some different ways of printing this character, but it always has the same result:

printf("test: %d\n", (signed char)'á');   // -31
printf("test: %d\n", (unsigned char)'á'); // 225
printf("test: %c\n", -31); // ß
printf("teste: %s\n", "á"); // ß
printf("test: %c\n", 225); // ß
printf("test: %d\n", 'á'); // -31
putc(-31, stdout); // ß

What I am doing wrong ?

jww
  • 97,681
  • 90
  • 411
  • 885
  • 1
    Looks like the wrong code page or C locale. – jww Jun 02 '18 at 20:43
  • What do you mean @jww ? – Matheus Benini Jun 02 '18 at 20:44
  • 1
    Also see [Character sets - Not clear](https://stackoverflow.com/q/3768363/608639) and [How to set run-time character set in C?](https://stackoverflow.com/q/13280620/608639) on Stack Overflow (and all the locale friends). – jww Jun 02 '18 at 21:06
  • 1
    The actual character displayed is also determined by the console window you are using and the character set that it supports. It could be you are trying to display characters that the console is not setup for. – cdarke Jun 02 '18 at 21:14

1 Answers1

0

It was a locale problem, as said in the comments of my question.

I just needed to use setlocale() and the output in the console worked.