如何修复 std::wcout 在 Linux 上打印问号 (?)

问题:

你正在尝试使用 std::wcoutwstring 字面量打印 wstring(使用 UTF-8 编码的源文件):

wstring_example.cpp
wstring w = L"Test: äöü";
wcout << w << endl;

但当你运行此程序时,你看到

wcout_output_questionmarks.txt
Test: ???

解决方案

使用 setlocale() 设置 UTF-8 区域设置:

wcout_locale_example.cpp
setlocale( LC_ALL, "en_US.utf8" );
wstring w = L"Test: äöü";
wcout << w << endl;

这将打印

wcout_output_utf8.txt
Test: äöü

如预期。

完整示例

wcout_full_example.cpp
#include <string>
#include <iostream>

using namespace std;

int main() {
    setlocale( LC_ALL, "en_US.utf8" );
    wstring w = L"Test: äöü";
    wcout << w << endl;
}

像这样编译:

build_wcout_example.sh
g++ -o main main.cpp

Check out similar posts by category: C/C++, Linux