I am trying to figure out how Unicode is supported in C++.
When I want to output multilingual text to console, I call std::setlocale
. However I noticed that the result depends on prior calls to setlocale
.
Consider the following example. If run without arguments it calls setlocale
once, otherwise it makes a prior call to setlocale
to get the value of current locale and restore it at the end of the function.
#include <iostream>
#include <locale>
using namespace std;
int main(int argc, char** argv)
{
char *current_locale = 0;
if (argc > 1) {
current_locale = setlocale(LC_ALL, NULL);
wcout << L"Current output locale: " << current_locale << endl;
}
char* new_locale = setlocale(LC_ALL, "ru_RU.UTF8");
if (! new_locale)
wcout << L"failed to set new locale" << endl;
else
wcout << L"new locale: " << new_locale << endl;
wcout << L"Привет!" << endl;
if (current_locale) setlocale(LC_ALL, current_locale);
return 0;
}
The output is different:
:~> ./check_locale
new locale: ru_RU.UTF8
Привет!
:~> ./check_locale 1
Current output locale: C
new locale: ru_RU.UTF8
??????!
Is there something that setlocale(LC_ALL, NULL)
does that needs to be taken care of in future setlocale
calls?
The compiler is g++ 7.5.0
or clang++ 7.0.1
. And the console is a linux console in a graphical terminal.
More details on the system config: OpenSUSE 15.1, linux 4.12, glibc 2.26, libstdc++6-10.2.1