cutf-8chinese-localesetlocalewchar

C programming language using locale.h to print UTF-8 characters


I want to print UTF-8 characters with C programming language. I've tried this but failed:

#include<stdio.h>
#include<stdlib.h>
#include<locale.h>
#include<wchar.h>

int main(){
    if(setlocale(LC_ALL, "zh-CN.UTF-8")!=NULL){
        printf("Error.\n");
    }
    wchar_t *hello=L"你好";
    wprintf(L"%ls\n", hello);
}

And the result:

$ gcc main.c
$ a
??

You can follow the link to see the picture: https://i.sstatic.net/PZKaa.png.

Can anyone help me?


Solution

  • setlocale returns NULL on error.

    You print an error message if setlocale returns something other than NULL, which means that the call succeeded. Your error message is not printed, so it appears that the call failed. That would explain the failure to turn the wchar_t* into UTF-8.

    You might want to figure out why setlocale is failing, although it's probably because that locale is not installed. Of course, you should change the test to make it correct; then you can try to use perror to get a sensible error message. (It's quite possible that setlocale doesn't set errno to anything useful on your system. Still, it's worth a try.)

        if(setlocale(LC_ALL, "zh-CN.UTF-8") == NULL){
            perror("setlocale failed");
            exit(1);
        }
    

    It's usually a bad idea to set the locale to anything other than "". The locale string "" is the locale currently configured in the terminal session, and you are relying on the terminal to correctly render the output. If you use a different locale than the terminal's, then output may be illegible.