Search code examples
ciso-8859-1

how to output degree symbol in C programs with iso_8859-1?


I looked up the manual of iso_8859-1 and found the degree symbol:

Oct   Dec   Hex   Char   Description
260   176   B0     °     DEGREE SIGN

Code:

int main( int argc, char *argv[])
{
    char chr = 176; //stores the extended ASCII of a symbol
    printf("Character with an ascii code of 251: %c \n", chr);
    return 0;
}

But it printed out as ?.

How could I output a degree symbol in a C programme? Do I need to include some files?


Solution

  • To use other characters than ASCII, on most platforms you have to switch to a "locale" that is able to handle such characters. At the beginning of your main you should have

       #include <locale.h>
       int main(void) {
         setlocale(LC_ALL, "");
       ...
       }
    

    here the empty string "" literally stands for the default locale of your platform.

    Now, what locale is supported by your platform is something that you'd have to find out yourself, you didn't give us enough information. I'd strongly suggest not to go with an obsolete one as you were proposing but to go for UTF-8.

    Usually you may embed UTF-8 character sequences naturally in normal C strings, so something like "105° C" should print out as the degree character.