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

无人久伴 提交于 2019-12-21 07:39:12

问题


Why

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

works well while

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

does not? (in Qt Creator for linux)


回答1:


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.



来源:https://stackoverflow.com/questions/18675720/cout-%d0%bf%d1%80%d0%b8%d0%b2%d0%b5%d1%82-or-wcout-l%d0%bf%d1%80%d0%b8%d0%b2%d0%b5%d1%82

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!