How to fix std::wcout printing question marks (?) on Linux

Problem:

You are trying to print a wstring from a wstring literal using std::wcout (with an UTF-8-encoded source file):

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

but when you run this program, you see

wcout_output_questionmarks.txt
Test: ???

Solution

Use setlocale() to set a UTF-8 locale:

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

This will print

wcout_output_utf8.txt
Test: äöü

as expected.

Full example

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;
}

Compile like this:

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

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