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

2019-04-04 23:02发布

Why

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

works well while

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

does not? (in Qt Creator for linux)

1条回答
可以哭但决不认输i
2楼-- · 2019-04-04 23:25

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.

查看更多
登录 后发表回答