Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cout<< "привет"; or wcout<< L"привет";

Why

cout<< "привет";

works well while

wcout<< L"привет";

does not? (in Qt Creator for linux)

like image 754
Minimus Heximus Avatar asked Sep 07 '13 16:09

Minimus Heximus


1 Answers

GCC and Clang defaults to treat the source file as UTF-8. Your Linux terminal is most probably configured to UTF-8 as well. So with cout<< "привет" there is a UTF-8 string which is printed in a UTF-8 terminal, all is well.

wcout<< L"привет" depends on a proper Locale configuration in order to convert the wide characters into the terminal's character encoding. The Locale needs to be initialized in order for the conversion to work (the default "classic" aka "C" locale doesn't know how to convert the wide characters). Use std::locale::global (std::locale ("")) for the Locale to match the environment configuration or std::locale::global (std::locale ("en_US.UTF-8")) to use a specific Locale (similar to this C example).

Here's the full source of the working program:

#include <iostream>
#include <locale>
using namespace std;
int main() {
  std::locale::global (std::locale ("en_US.UTF-8"));
  wcout << L"привет\n";
}

With g++ test.cc && ./a.out this prints "привет" (on Debian Jessie).

See also this answer about dangers of using wide characters with standard output.

like image 50
ArtemGr Avatar answered Oct 31 '22 21:10

ArtemGr