库特<< "привет" ;或 wcout<< L "привет" ;

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

本文关键字:lt wcout 库特      更新时间:2023-10-16

Why

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

工作良好,而

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

不?(在 Qt Creator for Linux 中)

GCC和Clang默认将源文件视为UTF-8。您的 Linux 终端很可能也配置为 UTF-8。因此,有了cout<< "привет"有一个 UTF-8 字符串,它打印在 UTF-8 终端中,一切都很好。

wcout<< L"привет"取决于正确的区域设置配置,以便将宽字符转换为终端的字符编码。需要初始化区域设置才能使转换正常工作(默认的"经典"又名"C"区域设置不知道如何转换宽字符)。对区域设置使用 std::locale::global (std::locale ("")) 以匹配环境配置,或std::locale::global (std::locale ("en_US.UTF-8"))使用特定区域设置(类似于此 C 示例)。

以下是工作程序的完整来源:

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

有了g++ test.cc && ./a.out,这打印了"привет"(在Debian Jessie上)。

另请参阅此答案,了解在标准输出中使用宽字符的危险。