Search code examples
c++setlocale

What exactly is the expected format of the locale in setlocale()?


If I use the fputws without setlocale, only ASCII letters get printed. It seems that setlocale is necessary, and according to this site, both setlocale(LC_CTYPE, "UTF-8") and setlocale(LC_CTYPE, "en_us.UTF-8") would work.

But when I tried it, setlocale(LC_CTYPE, "UTF-8") did not work, and it printed "Hello ". Only with setlocale(LC_CTYPE, "en_us.UTF-8"), I get "Hello ねこ 2". I read the comment on that page, and he also said "UTF-8" did not work (he used GCC, I used VC++). I read some manual pages, but they did not specifically say what the format should be. On CPP reference, the example is using only formats like "en_US.UTF-8", but on tutorials point, the example uses formats like "en_GB".

Is setlocale(LC_CTYPE, "UTF-8") a correct call?

setlocale(LC_CTYPE, "UTF-8");
//setlocale(LC_CTYPE, "en_us.UTF-8");
FILE* output = _wfopen(L"output.txt", L"w");
fputws(L"Hello ねこ 2", output);
fclose(output);

Solution

  • The answer is system specific. To quote the cppreference page you linked to:

    system-specific locale identifier. Can be "" for the user-preferred locale or "C" for the minimal locale

    I think "UTF-8" is an invalid locale name generally (it needs the language identifier at minimum, not 100% on that though). However generally you will want to simply use "" in order to default to the user preference (which, I would hope, is correct for displaying their input).